在旧 C 中使用前声明变量
最近,我必须修改使用非常旧的 GCC 版本(版本 2.3 左右)编译的遗留代码。在函数中,变量必须在使用之前声明。我相信这是C89标准所做的。此限制后来被删除。
我的问题是:当时他们为什么要执行这个裁决?是否存在任何可能危及软件完整性的问题?
Recently I had to modify a legacy code that was compiled with a very old version of GCC (somewhere around version 2.3). Within a function, variable had to be declared before being used. I believe this is done C89 standard. This limitation is later removed.
My question is: Back then, why did they enforce this ruling? Was there any concern that could jeopardise the integrity of the software?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
变量在使用之前仍然需要声明——而且它们从来不需要在函数的顶部声明。
C89 要求块由开始的
{
、后跟零个或多个声明、后跟零个或多个语句、后跟结束的}
组成。例如,这是合法的 C89(并且,没有
void
,甚至是 K&RC,可以追溯到 1978 年或更早):一点,允许声明和语句在块内混合:
C99 放宽了这 对于最初的限制,我认为它可以追溯到 C 的祖先语言:B、BCPL,甚至 Algol。它可能确实使编译器的工作变得更容易一些。 (我以为这会让解析变得更容易,但我不认为它会这样做;它仍然必须能够在事先不知道上下文的情况下区分某些东西是声明还是语句。)
Variables still have to be declared before being used -- and they've never had to be declared just at the top of a function.
The C89 requirement is that a block consists of an opening
{
, followed by zero or more declarations, followed by zero or more statements, followed by the closing}
.For example, this is legal C89 (and, without the
void
, even K&R C, going back to 1978 or earlier):C99 loosened this, allowing declarations and statements to be mixed within a block:
As for the reason for the original restriction, I think it goes back to C's ancestor languages: B, BCPL, and even Algol. It probably did make the compiler's job a bit easier. (I was thinking that it would make parsing easier, but I don't think it does; it still has to be able to distinguish whether something is a declaration or a statement without knowing in advance from the context.)
主要是为了让编译器更容易编写。如果所有声明都位于函数的顶部,则编译器将很容易解析所有局部变量并确定需要多少堆栈。
当然,现在编译器比 30 年前成熟很多。因此,摆脱这个限制是有意义的,因为它已经成为程序员的麻烦。
It was mainly to make compilers easier to write. If all the declarations were at the top of the function, it would be easy for the compiler to parse all the locals and determine how much stack is needed.
Of course now, compilers are a lot more mature than they were 30 years ago. So it makes sense to get rid of this restriction as it's become a nuisance to programmers.