我正在读一本书上的 C 编程,书中说所有变量都必须在函数的开头声明。我尝试了以下代码,但没有发出任何错误。我正在使用 mingw 和 codeblocks。代码如下:
#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)
最佳答案
all variables have to be declared in the beginning of the function.
准确地说,它们必须在 block 的开头声明。而且这只适用于 C89。 C99 取消了这个限制。因此,您可以将编译器更改为严格的 C89 模式。例如,对于 GCC,它是 -std=c89
选项。要获得标准所需的所有诊断,您还应该指定选项 -pedantic
。
为了演示我所说的在 block 的开头的含义,这是合法的 C89 语法:
void foo()
{
int x = 1;
x = x + 1;
{
int y = 42; /**OK: declaration in the beginning of a block*/
}
}
关于c - C mingw 中的变量声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19749997/