簡體   English   中英

C mingw中的變量聲明

[英]Variable declaration in C mingw

我正在從一本書中讀到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*/
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM