In this article, we are going to understand the switch-case construct in C Language.

Switch Case in C

The switch-case construct is an alternative to the if-else-if construct. Below code shows the general format of a switch-case construct:

switch (expression) {
  case constant_1 :	statement_1;
            break;

  case constant_2 :	statement_2;
            statement_3;
            break;
            ...
            ...

      default :	statement_n;
            break;
}

The expressions constants_1 to constant_n are known as constant-expressions. These can be constant values of type int or char and can also be expressions involving such constants.

The code fragments “case constant_1:” are known as case labels.

The expression must evaluate to an int or a char value.

The expression is evaluated first and its value is then matched against the case labels. When a match is found, the statements following that case will be executed.

If there is no match with any of the case labels, the statements following the default: case will be executed.

The default part is optional. If the default part is omitted and the integer value of the expression does not match with any of the available case labels, then no statement within the switch-case construct will be executed.

If a break; statement is not included in the case-statement, the execution control-flow will fall through into the subsequent case statement until it encounters a break statement.

Let us consider a sample problem that reads country_id and prints the country_name.

#include<stdio.h>
void main() {
     int country_id; 
     printf("Enter a country id value : ");
     scanf("%d", &country_id);
     switch (country_id) {
        case 1:
             printf("India\n");
             break;
        case 2:
             printf("United Statesof America\n");
             break;
        case 3:
             printf("United Kingdom\n");
             break;
        default:
             printf("Other Country\n");
      }
}

Output:

Enter a country id value : 1
India

References:

Happy Learning 🙂

I’m an Undergraduate Student at the Indian Institute of Information Technology, Design, and Manufacturing, Kurnool, Andhra Pradesh. I belong to the CSE domain.

Leave A Comment