15.04.2018 Views

programming-for-dummies

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

550<br />

Branching Statements<br />

switch (expression) {<br />

case value1:<br />

case value2:<br />

Command;<br />

break;<br />

case value3:<br />

case value4;<br />

Command;<br />

break;<br />

default:<br />

Command;<br />

}<br />

The preceding SWITCH statement is equivalent to the following IF-ELSEIF<br />

statement in C++:<br />

if (expression = value1) || (expression = value2) {<br />

Command;<br />

}<br />

else if (expression = value3) || (expression = value4) {<br />

Command;<br />

}<br />

else {<br />

Command;<br />

}<br />

One main difference between C# and Java is the way each language handles<br />

fall-through, where multiple CASE statements can run if a break command<br />

isn’t inserted into each one. Consider the following SWITCH statement in<br />

Java, which allows fall-through:<br />

switch (age) {<br />

case 17:<br />

case 18:<br />

case 19;<br />

case 20;<br />

System.out.println(“You’re too young to drink.”);<br />

case 21:<br />

System.out.println(“You’re old enough to drink.”);<br />

}<br />

In this example, the SWITCH statement will print the following if the value of<br />

age is 17, 18, 19, or 20:<br />

You’re too young to drink.<br />

You’re old enough to drink.

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

Saved successfully!

Ooh no, something went wrong!