by John
Kopp
Welcome to About.com's tutorial on C++ programming. This
lesson covers the topics of variable scope and lifetime. Every
object
in a program has an identifier
or name. Many complex questions arise from this seemingly
simple statement. Does each identifier need to be unique?
Where is an identifier valid? Where can it be used? Where can
it not? The answers to these questions are found by
understanding the concept of scope.
A variable's scope is the region of code in which the
compiler can uniquely resolve its identifier. Within a
particular scope, an identifier must be unique. In C++,
objects can have local,
global
(namespace) or class scope. A variable with local scope is
visible only within the function
or code block in which it is defined. Variables with global
scope are visible and can be used through out a program.
Variables have global scope (or namespace scope) if they are
defined in the part of the code that is outside of any class
or function definition. A class definition also delimits a
block of code and a scope.
Closely related to scope is the topic of lifespan or
lifetime. How long does a variable exist? Will it exists for
the entire duration of a program or only for the duration of a
function or method call? As we will see, an object's lifetime
depends largely on its scope.
Local Scope Functions or class methods
define a local scope. Code blocks delimited by brackets, {},
and certain statements also define local scopes. Variables
within a particular local scope can only be accessed by code
within that particular code block. Outside of the block, they
do not exist. Each identifier must be unique within a scope.
The compiler
must resolve each identifier within a scope to a particular
memory location. The definition
of an object allocates storage space for the object in memory.
During compilation, each name (identifier) must be resolved or
linked to a particular physical location in memory. This means
that every definition in a local scope must use a distinct
identifier.
To understand all of this, let's look at a few
examples.
Next
page > Example
1 > Page 1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11
|