11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 8: Taking a First Look at C++ Pointers 121Execution begins with main(). The function main() immediately invokesparent(). The first thing that the processor sees in parent() is the declarationof intParent. At that point, intParent goes into scope — that is,intParent is defined and available for the remainder of the functionparent().The second statement in parent() is the call to child(). Once again, thefunction child() declares a local variable, this time intChild. The variableintChild is within the scope of child(). Technically, intParent is notwithin the scope of child() because child() doesn’t have access tointParent; however, the variable intParent continues to exist.When child() exits, the variable intChild goes out of scope. Not only isintChild no longer accessible, but it no longer even exists. (The memoryoccupied by intChild is returned to the general pool to be used for otherthings.)As parent() continues executing, the variable intLater goes into scope atthe declaration. At the point that parent() returns to main(), both intParentand intLater go out of scope. The programmer may declare a variable outsideof any function. This type of variable, known as a global variable, remains inscope for the duration of the program.Because intGlobal is declared globally in this example, it is available to allthree functions and remains available for the life of the program.Examining the scope problemThe following code segment compiles without error but doesn’t work (don’tyou just hate that):double* child(void){double dLocalVariable;return &dLocalVariable;}void parent(void){double* pdLocal;pdLocal = child();*pdLocal = 1.0;}The problem with this function is that dLocalVariable is defined only withinthe scope of the function child(). Thus, by the time the memory address

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!