Understanding Scopes and Variable Lifetimes

C and C++ define scope rules, which govern the visibility and lifetime of objects. Although there are several subtleties, in the most general sense, there are two scopes: global and local.

The global scope exists outside all other scopes. A name declared in the global scope is known throughout the program. For example, a global variable is available for use by all functions in the program. Global variables stay in existence the entire duration of the program.

A local scope is defined by a block. That is, a local scope is begun by an opening brace and ends with its closing brace. A name declared within a local scope is known only within that scope. Because blocks can be nested, local scopes, too, can be nested. Of course, the most common local scope is the one defined by a function. Local variables are created when their block is entered, and destroyed when their block is exited. This means that local variables do not hold their values between function calls. You can use the static modifier, however, to preserve values between calls.

In C++ and C99, local variables can be declared nearly anywhere within a block. In C89, they must be declared at the start of a block, before any “action” statements occur. For example, the following code is valid for C++ and C99, but not for C89:

void f(int a) {   int a;   a = 10;   int b; // OK for C++ and C99, but not C89

A global variable must be declared outside of all functions, including outside the main( ) function. Global variables are generally placed at the top of the file, prior to main( ), for ease of reading and because a variable must be declared before it is used.

The formal parameters to a function are also local variables and, aside from their job of receiving the value of the calling arguments, behave and can be used like any other local variable.

C(s)C++ Programmer's Reference
C Programming on the IBM PC (C Programmers Reference Guide Series)
ISBN: 0673462897
EAN: 2147483647
Year: 2002
Pages: 539

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net