我从一本书中读到C编程,该书说所有变量必须在函数的开头声明。我尝试了以下代码,但未发出任何错误。我正在使用mingw和代码块。代码如下:
#include <stdio.h>
int main()
{
int i=10;
printf("%d\n",i);
int j=20;
printf("%d\n",j);
return 0;
}
我是否需要更改任何编译器设置或使其与本书给出的标准兼容的内容?
我正在使用-std = c89编译器选项。请参阅下面的编译消息:
-------------- Clean: Debug in HelloWorld (compiler: GNU GCC Compiler)---------------
Cleaned "HelloWorld - Debug"
-------------- Build: Debug in HelloWorld (compiler: GNU GCC Compiler)---------------
mingw32-gcc.exe -Wall -std=c89 -g -c D:\MyCodeBlocksProjects\HelloWorld\main.c -o obj\Debug\main.o
mingw32-g++.exe -o bin\Debug\HelloWorld.exe obj\Debug\main.o
Output size is 68.53 KB
Process terminated with status 0 (0 minutes, 0 seconds)
0 errors, 0 warnings (0 minutes, 0 seconds)
所有变量都必须在函数开头声明。
确切地说,必须在block的开头声明它们。这仅在C89中适用。C99已删除此限制。因此,您可以将编译器更改为严格的C89模式。例如,对于GCC,它是-std=c89
选项。要获得该标准所需的所有诊断信息,您还应该指定选项-pedantic
。
为了演示我在块开头的含义,这是合法的C89语法:
void foo()
{
int x = 1;
x = x + 1;
{
int y = 42; /**OK: declaration in the beginning of a block*/
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句