2012-03-01 69 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