Monday, September 29, 2008

Switch

The selective Structure: switch.

The syntax of the switch instruction is a bit peculiar. Its objective is to check several possible constant values for an expression, something similar to what we did at the beginning of this section with the linking of several if and else if sentences.  Its form is the following:
 switch (expression) {
  case constant1:
    block of instructions 1
    break;

case constant2:
    block of instructions 2

break;

 default:

 default block of instructions

  }



 
It works in the following way: switch evaluates expression and checks if it is equivalent to constant1, if it is, it executes block of instructions 1 until it finds the break keyword, then the program will jump to the end of the switch selective structure.



If expression was not equal to constant1 it will check if expression is equivalent to constant2. If it is, it will execute block of instructions 2 until it
finds the break keyword.



Finally, if the value of expression has not matched any of the previously specified constants (you may specify as many case sentences as values you want to check), the program will execute the instructions included in the default: section, if this one exists, since it is optional.
 

Both of the following code fragments are equivalent:

switch example

switch (x) {
  case 1:
    cout << "x is 1";
    break;
  case 2:
    cout << "x is 2";
    break;
  default:
    cout << "value of x unknown";
  }

if-else equivalent

if (x == 1)
{

cout << "x is 1";

}
else if (x == 2)
{

cout << "x is 2";

}

else
{

cout << "value of x unknown";

}

Source: cplusplus.com

No comments: