20.09.2015 Views

Programming in C

Kochan - ProgramminginC

Kochan - ProgramminginC

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.

84 Chapter 6 Mak<strong>in</strong>g Decisions<br />

The switch Statement<br />

The type of if-else statement cha<strong>in</strong> that you encountered <strong>in</strong> the last program example—<strong>in</strong><br />

which the value of a variable is successively compared aga<strong>in</strong>st different values—is<br />

so commonly used when develop<strong>in</strong>g programs that a special program statement exists <strong>in</strong><br />

the C language for perform<strong>in</strong>g precisely this function.The name of the statement is the<br />

switch statement, and its general format is<br />

switch ( expression )<br />

{<br />

case value1:<br />

program statement<br />

program statement<br />

...<br />

break;<br />

case value2:<br />

program statement<br />

program statement<br />

...<br />

break;<br />

...<br />

case valuen:<br />

program statement<br />

program statement<br />

...<br />

break;<br />

default:<br />

program statement<br />

program statement<br />

...<br />

break;<br />

}<br />

The expression enclosed with<strong>in</strong> parentheses is successively compared aga<strong>in</strong>st the values<br />

value1, value2, ..., valuen, which must be simple constants or constant expressions. If a<br />

case is found whose value is equal to the value of expression, the program statements<br />

that follow the case are executed. Note that when more than one such program statement<br />

is <strong>in</strong>cluded, they do not have to be enclosed with<strong>in</strong> braces.<br />

The break statement signals the end of a particular case and causes execution of the<br />

switch statement to be term<strong>in</strong>ated. Remember to <strong>in</strong>clude the break statement at the<br />

end of every case. Forgett<strong>in</strong>g to do so for a particular case causes program execution to<br />

cont<strong>in</strong>ue <strong>in</strong>to the next case whenever that case gets executed.<br />

The special optional case called default is executed if the value of expression does<br />

not match any of the case values.This is conceptually equivalent to the “fall through”<br />

else that you used <strong>in</strong> the previous example. In fact, the general form of the switch<br />

statement can be equivalently expressed as an if statement as follows:

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

Saved successfully!

Ooh no, something went wrong!