/* testfunc07.cpp CIS 150 2008-06-10 David Klick This program demonstrates variable scope. */ #include using std::cin; using std::cout; void changeXYZ(int n); // function prototype void cont(); int w = 3; // global variable int y = 5; // global variable int main(int argc, char* argv[]) { int x = 7; // seen only within main int y = 9; // seen only within main; hides global y int z = 11; // seen only within main // see what values are before function call cout << "Before calling changeXYZ: w=" << w << ", x=" << x << ", y=" << y << ", z=" << z << '\n'; changeXYZ(z); // try to change values // see what values are after function call cout << "After calling changeXYZ: w=" << w << ", x=" << x << ", y=" << y << ", z=" << z << '\n'; cont(); return 0; } /* void changeXYZ(int z); Arguments: int z: an arbitrary integer value Returns: nothing Try to change x, y, and z values. Variables x, y, and z are all local to calling function. Variable x is local to this function. Variable z's value is passed in as an argument. Variable y is also globally declared. */ void changeXYZ(int z) { int x = 2; // must declare since main's x can't be seen here y = 4; // changes global y z = 6; // tries to change value of z cout << "Inside changeXYZ: w=" << w << ", x=" << x << ", y=" << y << ", z=" << z << '\n'; } /* void cont(); Arguments: none Returns: nothing Clears input buffer and pauses waiting for user to press Enter. */ void cont() { if (cin.rdbuf()->sungetc() != -1 && cin.get() != '\n') cin.ignore(80,'\n'); cout << "Press enter to continue..."; cin.get(); } /* Sample output: Before calling changeXYZ: w=3, x=7, y=9, z=11 Inside changeXYZ: w=3, x=2, y=4, z=6 After calling changeXYZ: w=3, x=7, y=9, z=11 */