Switch Statements in C: Making Multiple Decisions in Your Code

 

Switch Statement in C

A switch statement is a control flow statement that allows you to choose between different code blocks based on the value of an expression. It’s often used to replace multiple if-else statements when comparing a single value against multiple possible cases.

Syntax:

switch (expression) {

    case value1:
        // Code to be executed if expression equals value1
        break;
    case value2:
        // Code to be executed if expression equals value2
        break;
    // ...
    default:
        // Code to be executed   
 if expression doesn't match any case
}
  • expression: The expression whose value is evaluated.
  • case value1, case value2, …: The possible values that the expression can take.
  • default: An optional case that is executed if the expression doesn’t match any of the other cases.

Example:

int day = 3;

switch (day) {
    case 1:
        printf("Mondayn");
        break;
    case 2:
        printf("Tuesdayn");
        break;
    case 3:
        printf("Wednesdayn");
        break;
    // ...
    default:
        printf("Invalid dayn");   
}

 

In this example, the switch statement evaluates the value of day and executes the corresponding case. If day is 3, the “Wednesday” case is executed.

Key Points:

  • The switch statement is useful for comparing a single value against multiple possible cases.
  • The break statement is essential to prevent fall-through to subsequent cases.
  • The default case is optional but recommended for handling unexpected values.
  • Multiple cases can share the same code block by omitting the break statement.
Switch Statements in C

Example with Shared Cases:

char grade = 'B';

switch (grade) {
    case 'A':
    case 'B':
    case 'C':
        printf("Passing graden");
        break;
    default:
        printf("Failing graden");
}

In this example, the cases for ‘A’, ‘B’, and ‘C’ share the same code block, indicating that they all represent passing grades.

A switch statement causes control to transfer to one labeled-statement in its statement body, depending on the value of expression . The values of expression and each constant-expression must have an integral type. A constant-expression must have an unambiguous constant integral value at compile time.

The switch statement evaluates an expression. The value of the expression is then compared with the values of each case in the structure. If there is a match, the associated block of code is executed. The switch statement is often used together with a break or a default keyword (or both).

Related Posts

Leave a Reply