Sams Teach Yourself C++ in 21 Days

(singke) #1
Organizing into Functions 111

5


6: {
7: using namespacestd;
8:
9: cout << “x from main: “ << x << endl;
10: cout << “y from main: “ << y << endl << endl;
11: myFunction();
12: cout << “Back from myFunction!” << endl << endl;
13: cout << “x from main: “ << x << endl;
14: cout << “y from main: “ << y << endl;
15: return 0;
16: }
17:
18: void myFunction()
19: {
20: using std::cout;
21:
22: int y = 10;
23:
24: cout << “x from myFunction: “ << x << endl;
25: cout << “y from myFunction: “ << y << endl << endl;
26: }

x from main: 5
y from main: 7

x from myFunction: 5
y from myFunction: 10

Back from myFunction!

x from main: 5
y from main: 7
This simple program illustrates a few key, and potentially confusing, points about
local and global variables. On line 4, two global variables,xand y, are declared.
The global variable xis initialized with the value 5 , and the global variable yis initial-
ized with the value 7.
On lines 9 and 10 in the function main(), these values are printed to the console. Note
that the function main()defines neither variable; because they are global, they are
already available to main().
When myFunction()is called on line 11, program execution passes to line 18, and on
line 22 a local variable,y, is defined and initialized with the value 10. On line 24,
myFunction()prints the value of the variable x, and the global variable xis used, just as

OUTPUT


LISTING5.5 continued


ANALYSIS
Free download pdf