0
$\begingroup$

Let's assume I have the following code:

declaration of a
declaration of b
..a..b
{
  ..a..b
  declaration of a 
  declaration of b
  ..a
}

In this code {} represent the inner block. declaration represents binding occurrence, and .. represent applied occurrence.

So my question is that is it legal to use the outer scope variables inside an inner scope and then redeclare them ? If so how does the hiding of outer variables system work (Does it start to work when it sees a redeclaration)? Thanks in advance.

$\endgroup$
2
$\begingroup$

It depends on the programming language. It's up to each language to specify whether this is legal or not, and what it means.

In many languages this would be legal. It is called variable shadowing.

| cite | improve this answer | |
$\endgroup$
2
$\begingroup$

It is in many languages legal to create a variable in an inner scope with the same name as a variable in an outer scope. The problem is that this may have been done by accident, and you never wanted to create a second variable, or that you use the inner variable when you wanted to use the outer one. For that reason, many compilers will issue a warning in that situation.

On the other hand, in Swift “if let x = x { ...}” is idiomatic. (It checks that the outer x is not nil, and makes its value accessible through the inner x).

| cite | improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.