我试图在ANSI C中做到这一点:
include <stdio.h>
int main()
{
printf("%d", 22);
int j = 0;
return 0;
}
这在 Microsoft 中不起作用 Visual C++ 2010(在 ANSI C 项目中)。你得到一个错误:
error C2143: syntax error : missing ';' before 'type'
这确实有效:
include <stdio.h>
int main()
{
int j = 0;
printf("%d", 22);
return 0;
}
现在我在很多地方读到,您必须在代码块的开头声明变量,这些变量存在于其中。这对于 ANSI C89 通常是正确的吗?
我发现很多论坛都提供了这个建议,但我没有看到它写在任何“官方”来源中,比如 GNU C。手动的。
最佳答案
ANSI C89 要求在作用域的开头声明变量。这在 C99 中得到了放松。gcc
清楚地表明了这一点当您使用 -pedantic
标志,它更紧密地执行标准规则(因为它默认为 C89 模式)。
但请注意,这是有效的 C89 代码:
include <stdio.h>
int main()
{
int i = 22;
printf("%d\n", i);
{
int j = 42;
printf("%d\n", j);
}
return 0;
}
但是使用大括号来表示一个范围(以及该范围内变量的生命周期)似乎并不是特别流行,因此 C99 ......等等。
关于c - 在作用域的开头声明 C89 局部变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9513604/