在作用域的开头声明C89局部变量? [英] Declare C89 local variables in the beginning of the scope?
问题描述
我试图在 ANSI C 中做到这一点:
I was trying to do this in ANSI C:
include <stdio.h>
int main()
{
printf("%d", 22);
int j = 0;
return 0;
}
这在 Microsoft Visual C++ 2010 中不起作用(在 ANSI C项目).你得到一个错误:
This does not work in Microsoft Visual C++ 2010 (in an ANSI C project). You get an error:
error C2143: syntax error : missing ';' before 'type'
这确实有效:
include <stdio.h>
int main()
{
int j = 0;
printf("%d", 22);
return 0;
}
现在我在很多地方读到你必须在变量存在的代码块的开头声明变量.对于ANSI C89来说这通常是真的吗?
Now I read at many places that you have to declare variables in the beginning of the code block the variables exist in. Is this generally true for ANSI C89?
我在很多论坛上找到了人们提供此建议的地方,但我没有看到它以任何官方"来源编写,例如 GNU C 手册.
I found a lot of forums where people give this advice, but I did not see it written in any 'official' source like the GNU C manual.
推荐答案
ANSI C89 要求在作用域的开始处声明变量.这在 C99 中变得轻松.
ANSI C89 requires variables to be declared at the beginning of a scope. This gets relaxed in C99.
当您使用 -pedantic
标志时,gcc
很清楚这一点,它更严格地执行标准规则(因为它默认为 C89 模式).
This is clear with gcc
when you use the -pedantic
flag, which enforces the standard rules more closely (since it defaults to C89 mode).
但请注意,这是有效的 C89 代码:
Note though, that this is valid C89 code:
include <stdio.h>
int main()
{
int i = 22;
printf("%d
", i);
{
int j = 42;
printf("%d
", j);
}
return 0;
}
但是使用大括号来表示范围(以及该范围内变量的生命周期)似乎并不特别流行,因此 C99 ......等
But use of braces to denote a scope (and thus the lifetime of the variables in that scope) doesn't seem to be particularly popular, thus C99 ... etc.
这篇关于在作用域的开头声明C89局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!