9.6 STATIC VARIABLES IN C


9.6 STATIC VARIABLES IN C++

The word static has three meanings in C++, while it has only one meaning in Java.

One meaning of static refers to its use as a qualifier for the data members or the member functions of a class. When a data member or a member function is declared static, it becomes a per class member, as opposed to the more common per object member. This use of static, mentioned rather briefly in Chapter 3, will be discussed more fully in Chapter 11. This is also how static gets used in Java.

The second meaning of static in C++ concerns its use for limiting the scope of a global variable or a function to the file in which they are defined. A global identifier that is static has internal linkage only, meaning that it cannot be linked to from another file with an extern declaration. This use of static, more common in older C++ code, is now discouraged. In modern programming practice, nameless namespaces are used to achieve the same effect (see Chapter 3).

It is the third meaning of static in C++ that is the focus of this section-the storage duration of a local variable in a function. When a local variable in C++ is declared to be static, it is stored in memory that does not get deallocated between the different invocations of the function. Consider the following example:

 
//StaticStorage.cc #include <iostream> using namespace std; void f() { static int m = 0; //(A) int n = 0; cout << "m = " << m++ << ", and n = " << n++ << endl; //(B) } int main() { f(); f(); f(); return 0; }

This code produces the following output

      m = 0, and n = 0      m = 1, and n = 0      m = 2, and n = 0 

The function f() contains two variables, a static variable m and a regular variable n. Both these variables are initialized to 0 and, in line (B), both are incremented in the cout statement. However, since m is static, during each invocation of f() the variable m retains its value from the previous invocation. In other words, the variable m persists from invocation to invocation of the function f() even though it is not visible outside that function. This persistence of m is reflected in the output produced by the program. Note that the initialization statement in (A) is executed only during the first invocation of f().




Programming With Objects[c] A Comparative Presentation of Object-Oriented Programming With C++ and Java
Programming with Objects: A Comparative Presentation of Object Oriented Programming with C++ and Java
ISBN: 0471268526
EAN: 2147483647
Year: 2005
Pages: 273
Authors: Avinash Kak

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