Wednesday, 9 May 2018

switch statement in C

switch statement in C – Part 1
 It is quite common that in day to day life we have to choose one option from several choices. Say if you have to choose only one desert out of the menu. Suppose if I give you a task to write a program for one menu. Probably you will use if-else ladder to make that. Well its good for now. But after reading this tutorial, I would suggest you to go with switch statements rather than anything else.
switch statement in C
This is the decision control instruction which allows the programmer to build a menu type program, so that the user can choose one options from multiple choices. It is also called switch-case-default instructions too because these are three keywords involved in making this instruction. Now lets head on to the syntax of switch statement.


switch(integer expression)
case constant 1: do this;
case constant 2: do this;
case constant 3: do this;
default: do this;

Explanation of this syntax

integer expression: It is used to check if programmer wants to execute the set of statements under switch or not. It works similar to conditions but we can only give integer expressions insider. It means an expression which is a integer or which evolves an integer.

case: It is the keyword to show multiple conditions inside switch statement. We can have any number of cases.

constant 1,2 and 3: As its name suggests these values should be either integer constant or character constant. Each value must be unique.

do this: We can use any legal C programming statement at that place.

default: It is another keyword which is used to execute some default statements if all conditions fails inside switch.

Now lets apply the above knowledge in some program.

void main ()
 int i=2;

  case 0: printf("No Message");
  case 1: printf("No Message");
  case 2: printf("This will print. n");
  case 3: printf("Even This will also print. n");
  default: printf("Default will also print.");