Why can’t a duplicate variable name be declared in a nested local scope?

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.

Leave a Comment