switch case control statement

Sign up for FREE 1 month of Kindle and read all our books for free.

Get FREE domain for 1st year and build your brand new site

A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.if variable and case value are matched, then matched case will be executed.
we can also say :-
The switch statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression.


switch (n)
    case 1: // code to be executed if n = 1;
    case 2: // code to be executed if n = 2;
    default: // code to be executed if n doesn't match any cases

Rules for Switch Case

The following rules apply to a switch statement −

  1. The expression provided in the switch should result in a constant value otherwise it would not be valid.

    // Constant expressions allowed

2.Duplicate case values are not allowed.

3.The default statement is optional.Even if the switch case statement do not have a default statement,
it would run without any problem.

4.The break statement is used inside the switch to terminate a statement sequence. When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.

5.The break statement is optional. If omitted, execution will continue on into the next case. The flow of control will fall through to subsequent cases until a break is reached.

6.Nesting of switch statements are allowed, which means you can have switch statements inside another switch. However nested switch statements should be avoided as it makes program more complex and less readable.



int main() 
   int x = 2; 
   switch (x) 
       case 1: printf("Choice is 1"); 
       case 2: printf("Choice is 2"); 
       case 3: printf("Choice is 3"); 
       default: printf("Choice other than 1, 2 and 3"); 
   return 0; 


Choice is 2

All the best