03.12.2012 Views

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

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.

2.2. VARIABLES 23<br />

2.2.3 Scope of variables<br />

Global definition: Every variable that we intend to use in a program must have been declared<br />

with its type specifier at an earlier point in the code. A variable can be either of global or local<br />

scope. A global variable is a variable that has been declared in the main body of the source<br />

code, outside all functions. After declaration, global variables can be referred from anywhere in<br />

the code, even inside functions. This sounds very handy because it is easily available but when<br />

your software grows it becomes more difficult and painful to keep track of the global variables’<br />

modifications. At some point, every code change bears the potential of triggering an avalanche<br />

of errors. Just do not use global variables. Sooner or later you will regret this. Believe us.<br />

Global constants like<br />

const double pi= 3.14159265358979323846264338327950288419716939;<br />

are fine because they cannot cause side effects.<br />

Local definition: Opposed to it, a local variable is declared within the body of a function<br />

or a block. Its visibility/availability is limited to the block enclosed in curly braces { } where<br />

it is declared. More precisely, the scope of a variable is from its definition to the end of the<br />

enclosing braces. Recalling the example of output streams<br />

int main ()<br />

{<br />

std::ofstream myfile(”example.txt”);<br />

myfile ≪ ”Writing this to a file. ” ≪ std::endl;<br />

return 0;<br />

}<br />

the scope of myfile is the from its definition to the end of function main. If we would write:<br />

int main ()<br />

{<br />

int a= 5;<br />

{<br />

std::ofstream myfile(”example.txt”);<br />

myfile ≪ ”Writing this to a file. ” ≪ std::endl;<br />

}<br />

myfile ≪ ”a is ” ≪ a ≪ std::endl; // error<br />

return 0;<br />

}<br />

then the second output is not valid because myfile is out of scope. The program would not<br />

compile and the compiler would tell you something like “myfile is not defined in this<br />

scope”.<br />

Hiding: If variables with the same name exist in different scopes then only variable is visible<br />

the others are hidden. A variables in an inner scope hides all variables in outer scopes. For<br />

instance: 3<br />

3 TODO: Picture would be nice.

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

Saved successfully!

Ooh no, something went wrong!