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.)