Tuesday 12 January 2010

C++ Syntax: Switch

C++ Syntax: switch
Description
The switch statement provides a convenient alternative to the if when dealing with a multi-way branch. Suppose we have some integer value called test and want to do different operations depending on whether it has the value 1, 5 or any other value, then the switch statement could be employed:-
switch ( test ) {

case 1 :
// Process for test = 1
...
break;

case 5 :
// Process for test = 5
...
break;

default :
// Process for all other cases.
...

}

It works as follows:-
The expression, just test in this case, is evaluated.
The case labels are checked in turn for the one that matches the value.
If none matches, and the optional default label exists, it is selected, otherwise control passes from the switch compound statement
If a matching label is found, execution proceeds from there. Control then passes down through all remaining labels within the switch statement. As this is normally not what is wanted, the break statement is normally added before the next case label to transfer control out of the switch statement. One useful exception occurs when you want to do the same processing for two or more values. Suppose you want values 1 and 10 to do the same thing, then:-
case 1 :
case 10:
// Process for test = 1 or 10
break;

works because the test = 1 case just "drops through" to the next section

No comments:

Post a Comment