Why can't variables be declared in an if state

2019-01-23 14:21发布

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 path leading to the program assigning 1 to b without declaring it first.

It occurred to me that b's variable scope might be limited to the first if statement, but then I wouldn't understand why. What if I really don't want to declare b needlessly, in order to improve performance? I don't like having variables left unused after declaration.

(You may want to argue than I could simply declare b in the second if statement, in that case, just imagine that it could be in a loop somewhere else.)

标签: java scope
13条回答
三岁会撩人
2楼-- · 2019-01-23 15:14

Why? There can be no code path leading to the program assigning 1 to b without declaring it first.

You are right, but the compiler doesn't know that. The compiler does not execute the code. The compiler only translates to bytecode without evaluating expressions.

查看更多
登录 后发表回答