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

Create successful ePaper yourself

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

2.5. CONTROL STATEMENTS 33<br />

The expression in the parentheses must be logic expression or something convertible to bool.<br />

For instance, one can write:<br />

int i;<br />

// ...<br />

if (i) // bad style<br />

do something();<br />

In the example, do something is called if i is different from 0. Experienced C and C ++ programmers<br />

know that (from heart) but the intentions of the developer are better communicated if<br />

this is stated explicitly:<br />

int i;<br />

// ...<br />

if (i != 0) // much better<br />

do something();<br />

The branches of if consist each of one single statement. To per<strong>for</strong>m multiple operations one can<br />

use braces: 12<br />

int nr then= 0, nr else= 0;<br />

// ...<br />

if (...) {<br />

nr then++;<br />

cout ≪ ”In then−branche\n”;<br />

} else {<br />

nr else++;<br />

cout ≪ ”In else−branche\n”;<br />

}<br />

In the beginning, it is helpful to always write the braces. With more experience, most developers<br />

only write the braces where necessary. At any rate it is highly advisable to intend the branches<br />

<strong>for</strong> better readable with any degree of experience.<br />

An if statement can contain other if-statements:<br />

if (weight > 100.0) {<br />

if (weight > 200.0)<br />

cout ≪ ”This is extremely heavy.\n”;<br />

else<br />

cout ≪ ”This is quite heavy.\n”;<br />

} else {<br />

if (weight < 50.0)<br />

cout ≪ ”A child can carry this.\n”;<br />

else<br />

cout ≪ ”I can carry this.\n”;<br />

}<br />

In the above example, the parentheses could be omitted without changing the behavior but it<br />

is clearer to have them. The example is more readable if we reorganize the nesting:<br />

if (weight < 50.0) {<br />

cout ≪ ”A child can carry this.\n”;<br />

} else if (weight

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

Saved successfully!

Ooh no, something went wrong!