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.

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

} else 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 />

It looks like the last line is executed when weight is between 100 and 200 assuming the first if<br />

has no else-branch. But we could also assume the second if comes without else-branch and the<br />

last line is executed when weight is less or equal 100. Fortunately, the C ++ standard specifies<br />

that an else-branch always belongs to the innermost possible if. So, we can count on our first<br />

interpretation. In case that the else-branch should belong to the first if we need braces:<br />

if (weight > 100.0) {<br />

if (weight > 200.0)<br />

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

} else<br />

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

Maybe these examples convinced you that it is more productive to set more braces and save<br />

the time guessing what the branches belong to.<br />

Advise<br />

If you use an editor that understands C ++ (like the IDE from Visual Studio<br />

or emacs in C ++ mode) then automatic indentation is a great help with<br />

structured programming. Whenever a line is not indented as you expected,<br />

something is most likely not nested as you intended.<br />

2.5.2 Conditional Expression<br />

Although this section describes statements, we like to talk about the conditional expression<br />

here because of its proximity to the if-statement. The semantic of<br />

condition ? result <strong>for</strong> true : result <strong>for</strong> false<br />

is that if the condition in first sub-expression evaluates to true then the entire expression is the<br />

second expression otherwise the third one. For instance, we can compute the minimum of two<br />

values with either if-then-else or the conditional expression:

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

Saved successfully!

Ooh no, something went wrong!