Tuesday, July 14, 2020

Digging Deeper into switch...case in C

Switch...case is similar to if...else but syntax of switch...case will be much easier compared to if...else. You won't get confused while using switch...case. Nested if...else will be more complex and may not be easier for the reader to decode the program, so switch...case will be the better option. It allow execution of one code block at a time based upon the value of the expression. 

If the expression doesn't match any of the constants in the case statement then default case will be executed. 

Syntax:

switch (expression)
​{
    case constant1:
      // statements
      break;

    case constant2:
      // statements
      break;
    .
    .
    .
    default:
      // default statements
}

Let us look into some examples for better understanding,

Example 1: 

#include<stdio.h>
int main()
{
int i;
for(i=1;i<=5;i++)
{
switch(i)
{
case 1:
case 2:
case 3:
case 5:
case 4: printf("A");
default: printf("C");
}
}
return 0;
}

Output:





  • In the above example there is no break in the case block. So in this kind of situation, all the case blocks below the matched case will be executed including default.
  • For executing a particular case block alone it should be terminated with break, otherwise case blocks below that case block will also be executed.
  • The order of the case doesn't matter. 
  • If the switch expression doesn't match with any of the case constants then default block will be executed.
  • default case can be placed anywhere inside the switch block.
Example 2:

float x = 1.5;
switch (x)
{
    case 1.1: printf("A"); 
    ....
}

The above code snippet will throw an error because the switch expression must be an integer type.

Example 3:

int x = 1.5;
switch (x)
{
    case 1printf("A");  break;

    case 1printf("B");  break;
    ....
}

The above code snippet will throw an compiler error because two case labels cannot have same value. We should not duplicate the case labels.

Example 4:

int x = 1.5;
int y;
switch (x)
{
    y = x; //statement inside switch
    case 1printf("A");  break;

    case 1printf("B");  break;
    ....
}

Note: Any statement inside the switch block other than the case statements will not be executed. It will be skipped by the compiler, it won't throw an error.

No comments:

Post a Comment

Exploring float data type in C

Float is one among the basic data type in C.  Floating point numbers in C has precision up to 6 decimal places.  T he header file float.h de...