Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are variables defined in a case block available in other case blocks? [duplicate]

Possible Duplicate:
Why are variables not local in case statements?

A variable defined in a scope block can't be used outside it. For example, the following code snippet is invalid:

{
    int anothervar = 4;
}
{
    System.out.println(anothervar);
}

But it looks like a case block does not create apart scopes.

switch (mode) {
    case ONE:
        dosomething();
        return;
    case TWO:
        int[] someints = new int[] { 2, 3, 5, 7 };
        SomeObject obj = new SomeObject();
        return;
    case THREE:
        someints = new int[] { 1, 4, 6, 8, 9 };
        obj = new SomeObject();
        return;
}

Why don't I have to declare someints inside the case THREE 'block'?
Suppose mode = THREE, then the declaration of variable someints is never reached, because case TWO, where someints is declared, is skipped. Or isn't it? How does it work internally?

(The chosen answer in Why are variables not local in case statements? states that a switch statement is internally a set of jump commands, but still that does not explain where the variable someints is declared.)

like image 443
MC Emperor Avatar asked Jan 04 '12 12:01

MC Emperor


1 Answers

a local variable's scope is inside a block, as specified in the Names documentation:

The scope of a local variable declaration in a block (§14.4.2) is the rest of the block in which the declaration appears, starting with its own initializer (§14.4) and including any further declarators to the right in the local variable declaration statement.

A block is defined to have enclosing braces, as written as well in the Blocks and Statements documentation:

A block is a sequence of statements, local class declarations and local variable declaration statements within braces.

like image 190
amit Avatar answered Sep 18 '22 14:09

amit