2013-04-08 82 views
6
if(someCondition) 
    int a=10;//Compilation Error 
else if(SomeOtherCondition){ 
int b=10;//no compilation Error 
} 

为什么会发生这种情况。为什么在第一种情况下出现编译错误。如果我把大括号,然后没有编译错误,但对于如果语句大括号是可选的,如果它是一个语句。if子句中的变量声明

回答

8

您需要在if statement中定义int a的范围,它将用花括号{}定义。

if(someCondition){ 
    int a=10; // works fine 
}else if(SomeOtherCondition){ 
    int b=10; //works fine 
} 
+1

谢谢你,这是完美的原因,我认为 – Krushna 2013-04-08 04:44:43

1
if(someCondition) 
    int a=10;//Compilation Error - you have to define the scope of int. what scope does it have here? so {} are necessary 
else if(SomeOtherCondition){ 
int b=10;//no compilation Error 
}