views:

142

answers:

6

I know in c++ variables have block scope, for example, the following code works in C++

void foo(){
    int a = 0;
    for(int i = 0; i < 10; ++i){
        int a = 1; //re-define a here.
    }

}

but this snippet doesnt work in java, it reports "duplicate local variable a", does it mean java variables dont have BLOCK scope?

+5  A: 

They have block scope. That means that you can't use them outside of the block. However Java disallows hiding a name in the outer block by a name in the inner one.

ybungalobill
+5  A: 

Good extended discussion about this can be found here: http://stackoverflow.com/questions/141140/why-does-java-not-have-block-scoped-variable-declarations

Andriy Sholokh
This should be a comment, not an answer.
Péter Török
+2  A: 

java variables do have a block scope but if you notice int a is already defined in scope

  { 
     int a = 0;
      {
       {
        } 
      }




   }

all subscopes are in scope of the uppermost curly braces. Hence you get a duplicate variable error.

sushil bharwani
+1  A: 

It does, but it's nested, so the "a" you defined in foo() is available in all blocks within foo.

Here is an example of what you're looking for:

void foo(){
    {
        int a = 0;
        // Do something with a
    }
    for(int i = 0; i < 10; ++i){
        int a = 1; //define a here.
    }
}
EboMike
+2  A: 

The previous answers already stated the reason, but I just want to show that this is still allowed:

void foo(){
    for(int i = 0; i < 10; ++i){
        int a = 1;
    }
    int a = 0;
}

In this case the a inside the loop doesn't hide the outer a, so it's valid.

Also IMHO it should be this way in C++ too, it's less confusing and prevents accidental declaration of variable with same name.

reko_t
+3  A: 

Section §14.4.2 says:

The scope of a local variable declaration in a block (§14.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.

The name of a local variable v may not be redeclared as a local variable of the directly enclosing method, constructor or initializer block within the scope of v, or a compile-time error occurs.

codaddict