15.04.2018 Views

programming-for-dummies

Create successful ePaper yourself

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

192<br />

Making Multiple Choices with the SELECT CASE Statement<br />

switch (Variable)<br />

{<br />

case X: Command #1;<br />

break;<br />

case Y: Command #2;<br />

}<br />

A SELECT CASE statement in BASIC might look like this:<br />

SELECT CASE Age<br />

CASE 65<br />

Status = Retired<br />

CASE 21<br />

Status – Working<br />

CASE 15<br />

Status = Student<br />

END SELECT<br />

The equivalent switch statement in C might look like this:<br />

switch (age)<br />

{<br />

case 65: status = retired;<br />

break;<br />

case 21: status = working;<br />

break;<br />

case 15: status – student;<br />

}<br />

The most crucial difference between the SELECT CASE statement in other<br />

languages and the switch statement in the curly bracket languages is the<br />

use of the break command. If you omit the break command, the switch<br />

statement doesn’t know when to stop running commands.<br />

In the preceding example, the break command stops the computer from<br />

running the other commands stored in the rest of the switch statement. So<br />

if the value of the age variable is 65, the preceding C program does the<br />

following:<br />

1. Set the status variable to retired.<br />

2. Stop running the switch statement.<br />

Suppose you didn’t include the break command, as follows:<br />

switch (age)<br />

{<br />

case 65: status = retired;<br />

case 21: status = working;<br />

case 15: status – student;<br />

}

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

Saved successfully!

Ooh no, something went wrong!