Global Variables
/* * Variables can be declared outside of any function, which gives them * global scope: That is, they are shared by all the functions which * don't have a local variable of the same name. */ #include <iostream> // The shared variable. int count = 0; // This shares the count variable. void f1(int amt) { count += amt; std::cout << "I am f1(" << amt << "): count = " << count << std::endl; } // This also shares the count variable. void f2(int amt) { count += amt; std::cout << "This is f2(" << amt << "): count = " << count << std::endl; } // This declares a variable count, so it does not have access to the // global. void f3(int amt) { // This declaration of a new variable count is said to "cover" // the global declaration. int count = 0; count += amt; std::cout << "Behold f3(" << amt << "): count = " << count << std::endl; std::cout << "The global one is " << ::count << std::endl; } // Another twist on it. void f4(int amt) { // This declaration also covers global variable count, but the // declaration static means that it lives between calls. static int count = 0; count += amt; std::cout << "And now!... f4(" << amt << "): count = " << count << std::endl; } int main() { f1(10); // f1 will add 10 to the global count and print it. f2(12); // f2 adds the 12 to the 10 in global count and print 22. f3(8); // f3 has a local count which covers the global. prints 8. f4(7); // f4 has a local static count. prints 7 but remembers it. f1(11); // f1 adds 11 to the global count and prints 33. f2(6); // f2 adds 6 to the global count and prints 39. f3(9); // f3's local count does not exist between calls. Prints 9. f4(3); // f4's local static remembers the 7 and becomes 10. }

Variables may be declared outside functions, which have global scope. That is, they can be used in any of the functions. That allows functions to share values without them being passed using parameters.

The wisdom of using globals is problematic, because it makes it harder for the reader of a program to understand what a function call does. It might depend on all sorts of previous behaviors which are not indicated in any parameter. It can be useful in languages like plain C which lack objects, and the global variable values can serve a purpose similar to data in an object. In an object-oriented language like C++, it's harder to find a good reason to use them. Generally, related data should be collected into a class, with methods that operate on it.

In the example, f4 contains a variable declared static. This variable is not shared with other functions, but between each invocation of f4, allowing one call to leave results for the next. It is given its initial value only once, when the program starts, not on each invokation as the normal variable in f3.

Textbook: pp. 246–247