switch statement in C – Part 3

Read: switch statement in C – Part 2

In the last tutorial I told you about the practical use of switch keyword. As I said earlier a programmer generally use this keyword for menu driven programs. Today I will tell you about the tips and traps while using switch keyword. I will also compare switch with if-else ladder.

So lets start it one by one.

switch statement in C

1. It is not compulsory to make switch-case statement for only integer expression. We can also make it for characters too.

#include<stdio.h>

void main()
{
 char i='z';
 switch(i)
 {
  case 'a':
  printf("This will print a");
  break;

  case 'z':
  printf("This will print z");
  break;

  case 'p':
  printf("This will print p");
  break;

  default:
  printf("Sorry its a mismatch");
 }
}

Output


switch statement in C - Part 3

2. We are not bound to write only one statement inside each case. And we can also put multiple conditions inside each case.

#include<stdio.h>

void main()
{
 char ans='Y';
 switch(ans)
 {
  case 'y':
  case 'Y':
  printf("It will check both small and capital Y alphabet");
  break;

   case 'n':
  case 'N':
  printf("It will check both small and capital N alphabet");
  break;
 }
}

Output


switch statement in C - Part 3

In the above program we have excluded the default column. As I said earlier its completely optional. You can also write multiple statements inside each case without worrying about the braces.

3. In case if you write a instruction inside switch case but it does not belong to any case. Then the compiler will skip that instruction at run time.

4. Switch statement can also be used to check the result of particular integer expression. E.g. switch(1*5*0+8*0)

5. You can also write nested switch statement but in practice it is used very rarely.

switch vs if-else

Advantages of using switch statement

1. It is a far better way of writing a program and it also gives well structured way to programs.

2. Switch statements works faster than if-else ladder because while the compilation of program, compiler generally generates a jump table by which it can easily check the answer instead of checking each condition.

Disadvantages of using switch

1. It doesn’t allow to write conditions with operators.

2. It doesn’t allow to write even floating point expression. e.g. switch (0.5) is not allowed.

3. A programmer cannot write multiple cases which will give same result.

case 8:
x=y;
break;

case 7+1:
k=2;
break;

Above code will give an error. Because two cases will give the same result i.e. 8.

Leave a Comment

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