Switch Case

 

Switch STATEMENT

 

The control statement which allows us to make a decision from the number of choices is called a switch, or more correctly a switch . . . case . . . default, since these three keywords go together to make up the control statement.

 

The switch statement tests the value of a given variable (or expression) against a list of case values and when a match is found, a block of statements associated with the case is executed. The syntax is :

 

switch (expression)

          {

                                    case value-1 :

                                                statement-1 ;

                                                break ;

                                    case value-2 :

                                                statement-2 ;

                                                break ;

                             .           .           .

                      .           .           .

               .           .           .

                                    default :

                                                default-statement ;

                        }

                        statement-x ;

 

Where the expression is an integer expression or characters. value-1, value-2 are constants or constant expression (valuable to an integral constant) and are known as case labels. Each of these values should be should be unique with a switch statement. statement-1, statement-2 are statement lists and may contain one or more statements. There is no need to put braces around these blocks. The keyword case is followed by an integer or a character constant. Each constant in each case must be different from all others and the case labels end with a colon (:).

 

When the switch is executed, the value is computed for expression, the list of possible constant expression values determined from all case statements is searched for a match. If a match is found, execution continues after the matching case statement and continues until a break statement is encountered or the end of statement is reached.

 

The break statement at the end of each block signals the end of a particular case and causes an exit from the switch statement, transferring the control to the statement-x following the switch. The default is an optional case. If a match is not found and the default statement prefix is found within switch, execution continues at this point. Otherwise, switch is skipped entirely and the control goes to the statement-x.

 

            Note : At the end of every case, there should be a break statement. Otherwise, it will result in causing the program execution to continue into the next case whenever case gets executed.

 

 

 

 

Registration


A password will be e-mailed to you.

Feedback Form

Name (required)

Email (required)

Feedback