/* * 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 // 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. }