Why can't variables be declared in an if statement?

前端 未结 13 1834
感动是毒
感动是毒 2020-12-05 10:18

The following Java code does not compile.

int a = 0;

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

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

Why? There can be no code pa

13条回答
  •  被撕碎了的回忆
    2020-12-05 10:55

    variable b's scope is only until the if block completes, as this is where you declared the variable. That is why it cannot be accessed on the following block. This is for memory allocation, otherwise they would be ALOT of variables floating around in the memory.

    int a = 0;
    
    if(a == 1) {
       int b = 0;    
    } //b scope ends here
    
    if(a == 1) {
        b = 1; //compiler error
    }
    

提交回复
热议问题