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.

Syntax


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.


Output


switch statement in C

Explanation

  • The program starts with integer variable i with value 2 in it.
  • After that I have written a switch keyword with one integer expression. i.e. switch(i). It means full switch statements will get executed if i=2 turns true.
  • I think you should have an idea that case 2 will get executed.
  • Now the turning point is after case 2, every statement get executed.
  • Even the last expression under default is also get executed.

Now an obvious question which should hit your mind.

Why is it so?
Well this is not the demerit of this program. In fact it’s the speciality of switch statements. It means if one condition turns true then all the subsequent conditions will also get executed inside switch statement. This is because it does not check any condition after getting a true value with one condition.

Switch statements are used very frequently in C programming. So I would recommend you to go through this tutorial at least once and make some programs by using switch keyword. In the next tutorial I will tell you about the method by which we can stop executing all the statements inside switch.

Leave a Comment

Your email address will not be published. Required fields are marked *