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.

24 CHAPTER 2. <strong>C++</strong> BASICS<br />

int main ()<br />

{<br />

int a= 5; // define #1<br />

{<br />

a= 3; // assign #1, #2 is not defined yet<br />

int a; // define #2<br />

a= 8; // assign #2, #1 is hidden<br />

{<br />

a= 7; // #2<br />

}<br />

} // end of #2’s scope<br />

a= 11; // #1, #2 is now out of scope<br />

return 0;<br />

}<br />

Defining the same variable name twice in the same scope is an error.<br />

The advantage of scopes is that you do not need to worry whether a variable (or something<br />

else) is already defined outside the scope. It is just hidden but does not create a conflict. 4<br />

Un<strong>for</strong>tunately, the hiding makes the homonymous variables in the outer scope inaccessible.<br />

Best thing you can do is to rename the variable in the inner scope (and eventually in the nextouter<br />

scope(s) to access more of those variables). Renaming the outermost variable also solves<br />

the problem of accessibility but tends to be more work because it is probably more often used<br />

due to its longer life time. A better solution to manage nesting and accessibility are namespaces,<br />

see next section.<br />

Scopes also have the advantage to reuse memory, e.g.:<br />

int main ()<br />

{<br />

int x, y;<br />

float z;<br />

cin ≫x;<br />

if (x < 4) {<br />

y= x ∗ x;<br />

// something with y<br />

} else {<br />

z= 2.5 ∗ float(x);<br />

// something with z<br />

}<br />

}<br />

The example uses three variables. However, they are never used at the same time. y is only<br />

used in the first branch and z only in the second one.<br />

Thus, we rewrite the program as follows<br />

int main ()<br />

{<br />

int x;<br />

cin ≫x;<br />

4 As opposed to macros, an obsolete and reckless legacy feature from C that should be avoided at any price<br />

because it undermines all structure and reliability of the language.

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

Saved successfully!

Ooh no, something went wrong!