12.12.2012 Views

Teach Yourself Borland C++ in 14 Days - portal

Teach Yourself Borland C++ in 14 Days - portal

Teach Yourself Borland C++ in 14 Days - portal

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

NOTE<br />

Wad<strong>in</strong>g In Deeper<br />

If the conditional expression evaluates to false, the code block associated with the if<br />

expression is ignored, and program execution cont<strong>in</strong>ues with the first statement follow<strong>in</strong>g the<br />

code block.<br />

<strong>C++</strong> conta<strong>in</strong>s a lot of shortcuts. One of those shortcuts <strong>in</strong>volves us<strong>in</strong>g<br />

just the variable name to test for true. Look at this code:<br />

if (fileGood) ReadData();<br />

This method is a shortcut for the longer form, which is illustrated with<br />

this l<strong>in</strong>e:<br />

if (fileGood == true) ReadData();<br />

This example uses a bool variable, but any data type will do. The<br />

expression evaluates to true as long as the variable conta<strong>in</strong>s any nonzero<br />

value. You can test for false by apply<strong>in</strong>g the logical NOT (!)<br />

operator to a variable name:<br />

bool fileGood = OpenSomeFile();<br />

if (!fileGood) ReportError();<br />

Learn<strong>in</strong>g the <strong>C++</strong> shortcuts will help you write code that conta<strong>in</strong>s a<br />

degree of elegance. Know<strong>in</strong>g the shortcuts also helps you understand<br />

<strong>C++</strong> code that you read <strong>in</strong> examples and sample list<strong>in</strong>gs.<br />

In some cases you want to perform an action if the conditional expression evaluates to true<br />

and perform some other action if the conditional expression evaluates to false. In this case<br />

you can implement the else statement:<br />

if (x == 20) {<br />

DoSometh<strong>in</strong>g(x);<br />

}<br />

else {<br />

DoADifferentTh<strong>in</strong>g(x);<br />

}<br />

NEW TERM<br />

The else statement is used <strong>in</strong> conjunction with the if statement and identifies<br />

sections of code that are executed when the if statement fails (that is, evaluates to<br />

false).<br />

In this example one of the two functions will be called, but not both.<br />

41<br />

2

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

Saved successfully!

Ooh no, something went wrong!