2013-11-03 98 views
2

我正在从一本书中读取C编程,该书说所有变量都必须在函数的开头声明。我尝试了下面的代码,但没有发出任何错误。我正在使用mingw和codeblocks。代码如下:C语言中的变量声明

#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) 
+0

添加'-std = c89'你的GCC命令行将使编译器C89模式。 –

+0

@JonathonReinhart我试着用-std = c89选项。请参阅上面的编译器消息。它仍然没有抱怨什么。需要更多设置? – abhithakur88

+0

因为它并不真正关心声明变量的位置,所以我不会惊讶地发现,如果你使用['-pedantic'](http:// gcc。 gnu.org/onlinedocs/gcc/Warning-Options.html),如[Yu Hao在下文中提到](http://stackoverflow.com/a/19750011/119527)。 –

回答

3

所有变量都在函数的开始申报。

准确地说,它们必须在区块的开头声明。这在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*/ 
    } 
}