Sams Teach Yourself C++ in 21 Days

(singke) #1
15: std::cout << “\nBack in main, x is: “ << x;
16: return 0;
17: }
18:
19: void myFunc()
20: {
21: int x = 8;
22: std::cout << “\nIn myFunc, local x: “ << x << std::endl;
23:
24: {
25: std::cout << “\nIn block in myFunc, x is: “ << x;
26:
27: int x = 9;
28:
29: std::cout << “\nVery local x: “ << x;
30: }
31:
32: std::cout << “\nOut of block, in myFunc, x: “ << x << std::endl;
33: }

In main x is: 5
In myFunc, local x: 8

In block in myFunc, x is: 8
Very local x: 9
Out of block, in myFunc, x: 8
Back in main, x is: 5
This program begins with the initialization of a local variable,x, on line 10, in
main(). The printout on line 11 verifies that xwas initialized with the value 5.
On line 13,MyFunc()is called.
On line 21 within MyFunc(), a local variable, also named x, is initialized with the value
8. Its value is printed on line 22.
The opening brace on line 24 starts a block. The variable xfrom the function is printed
again on line 25. A new variable also named x, but local to the block, is created on line
27 and initialized with the value 9. The value of this newest variable xis printed on
line 29.
The local block ends on line 30, and the variable created on line 27 goes “out of scope”
and is no longer visible.
When xis printed on line 32, it is the xthat was declared on line 21 within myFunc().
This xwas unaffected by the xthat was defined on line 27 in the block; its value is
still 8.

OUTPUT


108 Day 5


LISTING5.3 continued

ANALYSIS
Free download pdf