开发者

What is the scope of a Java variable in a block? [duplicate]

This question already has answers here: Why does Java not have block-scoped variable declarations? (6 answers) Closed 5 years ago.

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开发者_JS百科; // Redefine a here.
    }
}

But this snippet doesn't work in Java, it reports "duplicate local variable a", does it mean Java variables don't have BLOCK scope?


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.


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.


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.


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.


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.
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜