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.

52 Day 2<br />

SYNTAX<br />

amountOverSpeedLimit is equal to 10, a value of 20 is assigned to f<strong>in</strong>e, and so on. In each of<br />

the first three cases you see a break statement. The break statement is used to jump out of<br />

the switch block—it means that a case match<strong>in</strong>g the expression has been found, and the rest<br />

of the switch statement can be ignored. F<strong>in</strong>ally, you see the default statement. The code<br />

block follow<strong>in</strong>g the default statement will be executed if no match<strong>in</strong>g cases are found.<br />

Notice that cases 20 and 25 have no statements follow<strong>in</strong>g them. If the expression<br />

amountOverSpeedLimit evaluates to 20 or 25, those cases fall through and the next code block<br />

encountered will be executed. In this situation, the values 20, 25, or 30 will all result <strong>in</strong> the<br />

same code be<strong>in</strong>g executed.<br />

WARNING<br />

▼<br />

▼<br />

Don’t forget your break statements! Without break statements the<br />

switch will cont<strong>in</strong>ue on even after f<strong>in</strong>d<strong>in</strong>g a match and may execute<br />

code you didn’t <strong>in</strong>tend to be executed. Sometimes that is how you want<br />

your switch to perform, but most of the time it is not.<br />

Inclusion of the default statement is not mandatory. You could write a switch without a<br />

default statement:<br />

switch (x) {<br />

case 10 : DoSometh<strong>in</strong>g(); break;<br />

case 20 : DoAnotherTh<strong>in</strong>g(); break;<br />

case 30 : TakeABreak();<br />

}<br />

Note that there is no break statement follow<strong>in</strong>g the last case statement. Because this is the<br />

last l<strong>in</strong>e of the switch, there is no po<strong>in</strong>t <strong>in</strong> <strong>in</strong>clud<strong>in</strong>g the break statement for this l<strong>in</strong>e.<br />

As I said earlier, you might want to use a switch if you f<strong>in</strong>d that you have several if statements<br />

back-to-back. The switch is a bit clearer to others read<strong>in</strong>g your program.<br />

The switch statement:<br />

switch (expr) {<br />

case value_1:<br />

statements_1;<br />

break;<br />

case value_2:<br />

statements_2;<br />

break;<br />

.<br />

.<br />

.<br />

case value_n:<br />

statements_n;<br />

break;

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

Saved successfully!

Ooh no, something went wrong!