Tuesday, August 26, 2008

switch() case default

Lesson 6.2

Now the other way to make decisions is to use the switch() case statement.

The format is
switch(expression); {
case const value: syntax to execute; break;
default: syntax to execute; break;
}
Here is an example:-



When cnt is 1 the text One is displayed on the lcd.

When cnt is 2 the text Two and Three is displayed on the lcd. This is because, case 2, does not have a break, so it continues processing the next line.

When cnt is 3, Three is displayed on lcd.

When cnt is 4 or more unknown is displayed on lcd.


Note: The switch value can only be integer or char.

With case the break is important as illustrated in case 2 in the above example. So be sure to code correctly or you might get undesired results.

Note: default is optional.