THE SWITCH STATEMENT


You sometimes need to compare one value or expression to a whole series of possible values. One way to accomplish this is to create one if statement for each comparison. However, if you have more than four or five in a row, a switch statement is a better option.

The syntax for the switch statement is shown here:

 switch( value )   case constant value :     statements     ...     break;   case constant value :     statements     ...     break;   default :     statements     ...     break; } 

The switch statement allows you to set up a block of code that compares a variable or value with several constant values. It begins with the Visual C++ keyword switch, followed by opening and closing parentheses containing the variable you want to use as a basis for comparison. Following the switch statement is the body of code containing the comparison, in braces. Between these braces, you can insert one or more case statements, each of which defines a constant value to be compared against. You can also include an optional default statement as a sort of catchall. The default statement executes if all the previous case statements fail to result in a match. To better understand how the switch statement works, look at the following pseudo-code example:

 switch Temperature   case if it is 32 degrees stay in bed   case if it is 70 degrees play the lottery   default Just read the newspaper 

In this example, one value, the temperature, is compared to a number of different values. If any one value, as defined by a case statement, is equal to the value of the temperature, the programming statements associated with that value are executed.

Functionally, the switch and the if...else statements have similar capabilities. However, when performing many successive tests, the switch statement is easier to read. The following code listing illustrates the previous pseudo-code example:

 switch( intTemperature ) {   case 32 :     MessageBox::Show( "It's too cold, stay in bed!" );   break;   case 70 :     MessageBox::Show( "Let's play the lottery!" );   break;   default :     MessageBox::Show( "Time to read the newspaper!"); } 




Microsoft Visual C++ 2005 Express Edition Programming for the Absolute Beginner 2006
Microsoft Visual C++ 2005 Express Edition Programming for the Absolute Beginner 2006
ISBN: 735615381
EAN: N/A
Year: 2005
Pages: 131

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net