Lab 8: Experiment 10

Using a Twice-Declared Identifier in Outer Block

Issue: Suppose an identifier has two different declarations, one in an outer block and one in a nested inner block. If the name is accessed within the outer block, but after the inner block, which declaration is used?

Hypothesis: The closest definition will be used.

Proximity seemed to work out fine in the last experiment, so why not here?

The Experiment: If we move the statement that displays arg1, we can get an answer to our question:

int main()
{
  int arg1;
  arg1 = -1;
  ...
  {
    char arg1 = 'A';
  }
  cout << arg1 << endl;
}

Question #8.10.1: If -1 is printed, what does this mean? If A is printed, what does this mean?

Observation:

Question #8.10.2: What does the program display?

Conclusions:

Question #8.10.3: Is our hypothesis correct? How do you know? If it's not correct, what should it be?

This calls into question the "proximity" rule of thumb. It's not a matter of which declaration is seen last. Apparently that one close curly brace makes the difference.

Question #8.10.4: If proximity does not matter for resolving duplication declarations, what does?

Hint: look at the nesting of the curly braces. Consult the scoping rules for more help.


Back to the Lab Exercise  |  Forward to the Next Experiment
© 2003 by Prentice Hall. All rights reserved.
Report all errors to Jeremy D. Frens.