2012-03-01 70 views
2

我試圖做到這一點的ANSI C:在範圍的開頭聲明C89局部變量?

include <stdio.h> 
int main() 
{ 
    printf("%d", 22); 
    int j = 0; 
    return 0; 
} 

這並不在微軟Visual C++ 2010年的工作(在ANSI C項目)。你得到一個錯誤:

error C2143: syntax error : missing ';' before 'type' 

這不工作:

include <stdio.h> 
int main() 
{ 
    int j = 0; 
    printf("%d", 22); 
    return 0; 
} 

現在我在,你必須在代碼塊中的變量存在的開頭聲明變量很多地方讀這是一般對於ANSI C89是否正確?

我發現很多論壇在這裏提供這個建議,但是我沒有看到它寫在任何「官方」源文件中,例如GNU C手冊。

回答

3

ANSI C89要求在範圍的開始處聲明變量。這在C99中得到放鬆。

當您使用-pedantic標誌(這會更緊密地執行標準規則(因爲它默認爲C89模式))時,使用gcc可以清楚地看到這一點。

不過請注意,這是有效的C89代碼:

include <stdio.h> 
int main() 
{ 
    int i = 22; 
    printf("%d\n", i); 
    { 
     int j = 42; 
     printf("%d\n", j); 
    } 
    return 0; 
} 

但使用括號來表示一個範圍(因此該範圍變量的壽命)的似乎並不特別受歡迎,因此,C99 ...等

3

這對於C89來說絕對是正確的。 (你最好查看這些語言的文檔,例如書籍和標準,編譯器文檔通常只是說明編譯器支持的語言和ANSI C之間的差異。)

但是,許多「C89」編譯器允許你除非編譯器處於嚴格模式,否則幾乎可以在塊中的任何位置放置變量聲明。這包括GCC,可以使用-pedantic進入嚴格模式。 Clang默認爲C99目標,因此-pedantic不會影響您是否可以將變量聲明與代碼混合使用。

MSVC對C的支持相當差,我很害怕。它只支持C89(舊!)和幾個擴展。

2

Now I read at many places that you have to declare variables in the beginning of the code block the variables exist in. Is this generally true for ANSI C 89?

是的,這是需要在C89/C90標準的複合語句的語法:

(C90, 6.6.2 Compound statement, or block)

Syntax

compound-statement

{ declaration-list_opt statement-list_opt }

聲明必須是之前的語句塊。

C99通過允許在一個塊中混合聲明和語句來放寬這一點。在C99標準中:

(C99, 6.8.2 Compound statement)

Syntax

compound-statement:

{ block-item-list_opt }

block-item-list:

block-item

block-item-list block-item

block-item:

declaration

statement