Mid*_*lue 43 c gcc for-loop syntax-error
有人可以详细说明以下gcc错误吗?
$ gcc -o Ctutorial/temptable.out temptable.c
temptable.c: In function ‘main’:
temptable.c:5: error: ‘for’ loop initial declaration used outside C99 mode
Run Code Online (Sandbox Code Playgroud)
temptable.c:
...
/* print Fahrenheit-Celsius Table */
main()
{
for(int i = 0; i <= 300; i += 20)
{
printf("F=%d C=%d\n",i, (i-32) / 9);
}
}
Run Code Online (Sandbox Code Playgroud)
PS:我含糊地回忆起int i应该在for循环之前声明.我应该声明我正在寻找一个给出C标准历史背景的答案.
dfa*_*dfa 82
for (int i = 0; ...)
Run Code Online (Sandbox Code Playgroud)
是C99中引入的语法.要使用它,您必须通过-std=c99(或稍后的标准)传递给GCC 来启用C99模式.C89版本是:
int i;
for (i = 0; ...)
Run Code Online (Sandbox Code Playgroud)
编辑
从历史上看,C语言总是迫使程序员在块的开头声明所有变量.所以类似于:
{
printf("%d", 42);
int c = 43; /* <--- compile time error */
Run Code Online (Sandbox Code Playgroud)
必须改写为:
{
int c = 43;
printf("%d", 42);
Run Code Online (Sandbox Code Playgroud)
块定义为:
block := '{' declarations statements '}'
Run Code Online (Sandbox Code Playgroud)
C99,C++,C#和Java允许在块中的任何位置声明变量.
真正的原因(猜测)是在解析C源时尽快分配内部结构(如计算堆栈大小),而不需要另外编译器传递.