Showing posts with label switch statement in c. Show all posts
Showing posts with label switch statement in c. Show all posts

Thursday 17 October 2013

Switch In C++

Switch In C++:

There are two branches or structures in C++ and we studied the first structure in our previous tutorial which was implemented with if and if…else statements. The second selection structure that we are going to study in this C tutorial for beginners is called the switch in c structure. This structure doesn’t require a logical evaluation.

Syntax:

         Switch (expression)
           {
                   case value1:
                       Statements1;
                       break;
                   case value2:
                       Statements2;
                       break;
                       .
                       .
                       .
                   case valuen:
                       Statementsn;
                       break;
                   default:
                       statements
              }





In C++, switch, case, break and default are reserved keywords. In this structure first the expression is evaluated and then that value gained by expression is used to perform action specified in the statements of the switch case in c that satisfies.
 The expression can be a constant or identifier. The expression is also called selector. Only one switch case c is executed and if none of the case satisfies then default case is executed. It is not important that break statement must appear after every each statement in the case.

Rules:

Below are some rules that the c switch statements follows:
When the value of the expression satisfies some case then the statements in that case execute until a break statement is reached or the end of the switch structure is reached.
If the value doesn’t match any case then the statements in default label executes. But if value of the expression doesn’t match any case and there is no default value then the entire switch structure is skipped.
A break statement causes an immediate exit from the switch structure.

Comparison between if…else and switch statement c:

Switch structure is more classified and easy to handle structure than if…else structure. In switch structure, user can easily track his/her cases.

Final Words:

C switch statement has been discussed in this c tutorial for beginners.switch statement in c is important  in C as it used to select between different expressions , and execute the one most appropriate under certain conditions.