Lab 8: Experiment 11

Non-Local Scope

Issue: Is there anywhere in a program that a name declared outside all blocks cannot be accessed?

In all of the rules of scope, an identifier's scope always begins as soon as its declared, never before. The question is always when the scope ends. The local scopes are all controlled by a closing curly brace. But this non-local scope extends all the way to the end of the file.

In fact, we started using this non-local scope as soon as we wrote our first C++ program:

#include <iostream>

This library declares cin and cout as non-local variables for us everywhere in the file immediately after the #include. To see this, comment out the line with the #include directive and recompile.

Question #8.11.1: What error does the compiler give you for this program?

Keeping in mind the importance of where variables, even non-locals, are declared, uncomment the #include and move it to the end of the file. Compile the program again.

Question #8.11.2: What error does the compiler give you for this program?

Question #8.11.3: Compare and contrast the two error messages you just saw.

Now maybe the sequencing of items in a code file makes more sense:

Question #8.11.4: Why are the #includes positioned at the beginning of a file (as opposed to the end of a file)?

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