C错误:int之前的预期表达式

当我尝试以下代码时,我得到了提到的错误。

if(a==1) int b =10; 

但以下在语法上是正确的

 if(a==1) { int b = 10; } 

为什么是这样?

这实际上是一个相当有趣的问题。 它并不像最初看起来那么简单。 作为参考,我将基于N1570中定义的最新C11语言语法

我想这个问题的反直觉部分是:如果这是正确的C:

 if (a == 1) { int b = 10; } 

那为什么这也不正确?

 if (a == 1) int b = 10; 

我的意思是,一行有条件if语句应该没有大括号,对吧?

答案在于if语句的语法,由C标准定义。 我在下面引用的语法的相关部分。 简洁地说: int b = 10行是声明 ,而不是语句if语句的语法需要在它测试的条件之后的语句。 但是如果你把声明括在括号中,它就会变成一个陈述,一切都很好。

而且只是为了完全回答这个问题 – 这与范围无关。 存在于该范围内的b变量将无法从其外部访问,但程序在语法上仍然是正确的。 严格来说,编译器不应该抛出错误。 当然,你应该用-Wall -Werror反正;-)

 (6.7) 声明声明特定的init-declarator-list opt ;
             static_assert声明

 (6.7) init-declarator-list初始化声明符
             init-declarator-list  init-declarator

 (6.7) init-declarator声明符
             declarator = 初始化器

 (6.8) 声明标记的声明
             复合语句
             表达式语句
             选择语句
             迭代语句
             跳转语句

 (6.8.2) 复合声明{ block-item-list opt }

 (6.8.4) 选择陈述if( 表达式  语句
             if( 表达式  语句 else 语句
             switch( 表达式  语句

{ } – >

定义范围,所以if(a==1) { int b = 10; } if(a==1) { int b = 10; }说,你正在为{} – 这个范围定义int b。 对于

 if(a==1) int b =10; 

没有范围。 你无法在任何地方使用b

通过C89,变量只能在块的顶部定义。

 if (a == 1) int b = 10; // it's just a statement, syntacitially error if (a == 1) { // refer to the beginning of a local block int b = 10; // at the top of the local block, syntacitially correct } // refer to the end of a local block if (a == 1) { func(); int b = 10; // not at the top of the local block, syntacitially error, I guess }