Multiple selection conditional structure: switch

    This structure allows the definition of two or more blocks of code. Wich one of them is executed depends on some numerical expression, because each block is attached to some possible numercal value. The beggining of the structure is indicated by the keyword switch and followed by the numerical expresion to evaluate (surrounded by parenthesis). Then, inside braces ({}), came the possible values (also numerical expresions), each of them with a block of code attached as follows: first the keyword case, then the value and a colon (:), then the actions to be performed when the expresion's value matches this case, and then a break; statement. When the program reaches that point, the expresion is evaluated, and compared to the posible cases in the same order as the appear in the source code. When a value matches, the actions after it are executed until the program reaches the end of the structure, or until it reaches a break; statement. That means that if there is no break after the actions for a case, when the program run into this case, it will follow with all the cases after that one until it finds a break. This is usefull when you want to attach the same actions to more than one possible values. There is also an especial case, introduced by the keyword default followed directly by a colon, that can be at the end and contains the actions to be executed when none of the previous cases match the expression's value.


Example:

    switch (num) {
    case 1:
       cout<<"Selection: 1"<<endl;
       break;
    case 2: case 3: case 4;
       cout<<"Selection: 2, 3 or 4"<<endl;
       break;
    case 5:
       cout<<"Selection: 5"<<endl;
       break;
    default:
       cout<<"Selection: greater than 5"<<endl
    };