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

前端 未结 13 1820
感动是毒
感动是毒 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:54

    The scope of b is the block it is declared in, that is, the first if. Why is that so? Because this scoping rule (lexical scoping) is easy to understand, easy to implement, and follows the principle of least surprise.

    If b were to be visible in the second if:

    • the compiler would have to infer equivalent if branches and merge them to a single scope (hard to implement);
    • changing a condition in a random if statement would potentially make some variables visible and others hidden (hard to understand and source of surprising bugs).

    No sane language has such a complicated scoping rule.

    w.r.t. performance - declaring an extra variable has a negligible impact on performance. Trust the compiler! It will allocate registers efficiently.

提交回复
热议问题