[英]Variable declaration in C mingw
I was reading C programming from a book that says all variables have to be declared in the beginning of the function. 我正在从一本书中读到C编程,该书说必须在函数的开头声明所有变量。 I tried following code but didn't issue any error. 我尝试了以下代码,但未发出任何错误。 I am using mingw and codeblocks. 我正在使用mingw和代码块。 The code is as follows: 代码如下:
#include <stdio.h>
int main()
{
int i=10;
printf("%d\n",i);
int j=20;
printf("%d\n",j);
return 0;
}
Do I have to change any compiler setting or something to make it compatible with the standard given in the book? 我是否需要更改任何编译器设置或使其与本书中给出的标准兼容的内容?
I am using -std=c89 compiler option. 我正在使用-std = c89编译器选项。 See the compilation messages below: 请参阅下面的编译消息:
-------------- 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. 所有变量都必须在函数开头声明。
To be precise, they have to be declared in the beginning of a block . 准确地说,必须在block的开头声明它们。 And this is only true in C89. 这仅在C89中适用。 C99 has removed this limit. C99已删除此限制。 So you can change your compiler to strict C89 mode. 因此,您可以将编译器更改为严格的C89模式。 For example, for GCC, it's -std=c89
option. 例如,对于GCC,它是-std=c89
选项。 To obtain all the diagnostics required by the standard, you should also specify the option -pedantic
. 要获得该标准所需的所有诊断,还应该指定选项-pedantic
。
To demonstrate what I mean by in the beginning of a block , this is legal C89 syntax: 为了演示我在块开头的含义,这是合法的C89语法:
void foo()
{
int x = 1;
x = x + 1;
{
int y = 42; /**OK: declaration in the beginning of a block*/
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.