在C变量声明安置 [英] Variable declaration placement in C
问题描述
我一直认为,在C,所有变量都必须在函数的开始申报。我知道,在C99中,规则是一样的在C ++中,但什么是变量声明放置规则为C89 / ANSI C?
I long thought that in C, all variables had to be declared at the beginning of the function. I know that in C99, the rules are the same as in C++, but what are the variable declaration placement rules for C89/ANSI C?
以下code与成功编译的gcc -std = C89
和的gcc -ansi
:
#include <stdio.h>
int main() {
int i;
for (i = 0; i < 10; i++) {
char c = (i % 95) + 32;
printf("%i: %c\n", i, c);
char *s;
s = "some string";
puts(s);
}
return 0;
}
不应该的C中的声明
和取值
引起C89 / ANSI模式错误?
Shouldn't the declarations of c
and s
cause an error in C89/ANSI mode?
推荐答案
它编译成功,因为GCC允许它作为一个GNU扩展,即使它不是C89或ANSI标准的一部分。如果要严格遵守这些标准,你必须通过 -pedantic
标记。
It compiles successfully because GCC allows it as a GNU extension, even though it's not part of the C89 or ANSI standard. If you want to adhere strictly to those standards, you must pass the -pedantic
flag.
这篇关于在C变量声明安置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!