Pages

Wednesday, 9 May 2018

switch statement in C – Part 2


switch statement in C – Part 2

switch statement in C
So we need a syntax that will execute only a certain set of statements when the condition turns true. So lets checkout the advance modification of switch statement with break keyword.

Syntax
switch(integer expression)
{
case constant 1: Statement 1;
break;

case constant 2; Statement 2;
break;
. . . . . .
. . . . . .

default: Statement 3;
}

Explanation of the above syntax
Well the whole syntax is almost same. But in the above syntax we have added break keyword after the cases. Remember we generally do not use continue keyword with switch.

Working of break keyword in switch statement
As you can see I have given break keyword after every case. Its working in switch case is almost same as in loops. If the compiler encounters break keyword in switch then it will take the control to the outside of switch block.
Flowchart of switch statement in C #include<stdio.h>

void main()
{
 int i=10;

 switch(i)
 {
  case 1: printf("Hey its 1");
   break;

  case 10: printf("Hey its 10");
    break;

  case 7: printf("Hey its 7");
   break;

  default: printf("Hey its default");
 }
}