c - C mingw 中的变量声明

标签 c variable-declaration

我正在读一本书上的 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/

相关文章:

objective-c - 如何交换big 到主机int8 数字?

c - 尝试计算文件中的单词数

postgresql - 在plpgsql中声明多个相同类型的变量有什么捷径吗?

java - 图形用户界面-JFrame : declaring variables

c - OpenCV 和 C,cvPreprocessCategoricalResponses 中的错误参数(响应 #0 不是整数)

c - 二叉搜索树插入程序显示段错误

c - 内核的 "container_of"- 有什么方法可以使其符合 ISO 标准吗?

java - 将 boolean 值设置为 false 是多余的吗?

swift - Swift REPL 中的变量声明必须有初始值

python - 像 Python 这样简单易学的语言,但需要声明变量?