为什么不能在一个嵌套的局部范围内重复的变量名声明?嵌套、范围内、在一、局部

2023-09-02 21:08:15 作者:江湖同醉

根据最近这次question,我不明白,提供了答案。好像你应该​​能够做这样的事,因为他们的范围不重叠

 静态无效的主要()
{
  {
    INT I;
  }
  INT I;
}
 

这code编译失败,出现以下错误:

  

,命名为I不能在此范围内声明,因为以'我',将给予不同的意义的局部变量它已经用在'孩子'范围来表示别的东西

解决方案

我不认为任何的答案至今的非常的得到了规范的重要线路。

从第8.5.1节:

  

在局部变量声明的是块声明的局部变量的范围,该声明所在。这是一个错误引用一个局部变量在于precedes局部变量的局部变量声明的文本位置。在局部变量的范围内,这是一个编译时错误声明另一个局部变量或常量具有相同的名称。

(重点煤矿。)

java 同一方法相同变量名 变量类型为什么不冲突 变量作用域相同

在换句话说,适用范围为后来的变量包含块的一部分的在的声明 - 即它包含有早变量内块

您不能的引用的到后来的变量在一个地方早于它的声明 - 但它仍然在范围

Based on this recent question, I don't understand the answer provided. Seems like you should be able to do something like this, since their scopes do not overlap

static void Main()
{
  {
    int i;
  }
  int i;
}

This code fails to compile with the following error:

A local variable named 'i' cannot be declared in this scope because it would give a different meaning to 'i', which is already used in a 'child' scope to denote something else

解决方案

I don't think any of the answers so far have quite got the crucial line from the spec.

From section 8.5.1:

The scope of a local variable declared in a local-variable-declaration is the block in which the declaration occurs. It is an error to refer to a local variable in a textual position that precedes the local-variable-declarator of the local variable. Within the scope of a local variable, it is a compile-time error to declare another local variable or constant with the same name.

(Emphasis mine.)

In other words, the scope for the "later" variable includes the part of the block before the declaration - i.e. it includes the "inner" block containing the "earlier" variable.

You can't refer to the later variable in a place earlier than its declaration - but it's still in scope.