11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Variable Storage TypesChapter 6: Creating Functions 91Function variables are stored in three different places. Variables declaredwithin a function are said to be local. In the following example, the variablelocalVariable is local to the function fn():int globalVariable;void fn(){int localVariable;static int staticVariable;}The variable localVariable doesn’t exist until execution passes throughits declaration within the function fn(). localVariable ceases to existwhen the function returns. Upon return, whatever value that is stored inlocalVariable is lost. In addition, only fn() has access to localVariable —other functions cannot reach into the function to access it.By comparison, the variable globalVariable is created when the programbegins execution — and exists as long as the program is running. All functionshave access to globalVariable all the time.The static variable staticVariable is a sort of mix between a local and aglobal variable. The variable staticVariable is created when executionfirst reaches the declaration — at roughly when the function fn() is called.The variable is not destroyed when program execution returns from the function.If fn() assigns a value to staticVariable once, it’ll still be there thenext time fn() is called. The declaration is ignored every subsequent timeexecution passes through.In case anyone asks, there is a fourth type, auto, but today it has the samemeaning as local, so you rarely (if ever) see that declaration type anymore.So whoever asked you about it is probably just being a show off (or showinghis age).Including Include FilesIt’s common to place function prototypes in a separate file (called an includefile) that the programmer can then include in her C++ source files. Doing sosets the stage for a C++ preprocessor program (which runs before the actualcompiler takes over) to insert the contents of a file such as filename, at thepoint of a statement such as #include “filename”.

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

Saved successfully!

Ooh no, something went wrong!