Search This Blog

If you like any posts in this blog then click this icon which is present under the post

Friday, 29 July 2011

Switch case statement


Switch statement is an extension of if else statement. This permits any number of branches. The general form is

switch(expression)
{
                case label1:
                                statement block-1;
                                break;
                case label2:
                                statement block-2;
                                break;
-----------------------------------------
-----------------------------------------
                case labeln:
                                statement block-n;
                                break;
                default       :
                                default statement;
                                break;
}



When this statement is executed the computer first evaluates the value of the expression in the keyword switch. This value is successfully compared with the case label1, label2… labeln. If a case label matches with the value, the statement block associated with the case label is executed. Then the control is transferred to the next statement.

If none of the case matches with the value, the default statement block is executed.

Rules
1. The expression should be placed in parentheses.
2. The value of the expression should be an integer.
3. The body of the switch statement should be enclosed within {} brackets.
4. Case label should terminate with a colon.
5. Break statement is a must and causes immediate exit from switch statement. If it is not included the statements below the matched case will be executed.

Flow Diagram

No comments:

Post a Comment

Followers