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 with the same name in the same block.
There's a Dr. Seuss story "Too Many Daves" about a mother who names all of her sons "Dave". Which Dave should respond when the mother calls "Come here, Dave!"? There's too much ambiguity, and compilers hate ambiguity, so it's unlikely that the compiler will like the same identifier used twice 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's redeclared as a
char
within the same block. When the program goes to display
arg1
at the very end, 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?
Do not change your program back.