Lab 8: Experiment 7


Too Many Daves ------- by Dr. Seuss
 
Did I ever tell you that Mrs. McCave
Had twenty-three sons, and she named them all Dave?
Well, she did. And that wasn't a smart thing to do.
You see, when she wants one, and calls out "Yoo-Hoo!
Come into the house, Dave!" she doesn't get one.
All twenty-three Daves of hers come on the run!
 
This makes things quite difficult at the McCaves'
As you can imagine, with so many Daves.
And often she wishes that, when they were born,
She had named one of them Bodkin Van Horn.
And one of them Hoos-Foos. And one of them Snimm.
And one of them Hot-Shot. And one Sunny Jim.
Another one Putt-Putt. Another one Moon Face.
Another one Marvin O'Gravel Balloon Face.
And one of them Zanzibar Buck-Buck McFate...
 
But she didn't do it. And now it's too late.

Same Identifier Declared Twice in Same Local Scope

Mrs. McCave had difficulty specifying which child was to respond when she called "Come here, Dave." In this experiment we look at a similar problem — when a program contains two or more variables or constants with the same name. If these do not occur in the same block of code as when an argument in a function call has the same name as one of the function's parameters, we would probably guess, based on our earlier experiments, that the compiler will have no problem with this. But if the same identifier is used twice in the same block, we might guess that it cannot deal with this ambiguity.

Issue: What happens if we declare the same name twice within a block, giving it two different meanings?

Hypothesis: The compiler will not accept two variables (or constants) with the same name in the same block.

Experiment: Add a declaration and an output just before the end of the main function:

int main()
{
  int arg1;
  arg1 = -1;
  ...
  char arg1 = 'A';
  cout << arg1 << endl;
}
The variable arg1 is declared near the beginning of the main function as the name of an int and it is redeclared as a char within the same block. When the program tries to display arg1 in the last statement, which one should it use? Using the closest declaration seems reasonable and not particularly ambiguous; perhaps our hypothesis is wrong...

Observation: Compile and execute your program.

Question #8.7.1: Did your program compile? If so, what does it print? If not, what error message did you get?

Conclusion: What's the verdict?

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

Keep the program the same for the next experiment.


Back to the Lab Exercise  |  Forward to the Next Experiment


Report errors to Larry Nyhoff (nyhl@cs.calvin.edu)