Switch Statements in C

Switch Statements in C: Making Multiple Decisions in Your Code




(toc)

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("Monday\n");
        break;
    case 2:
        printf("Tuesday\n");
        break;
    case 3:
        printf("Wednesday\n");
        break;
    // ...
    default:
        printf("Invalid day\n");   
}

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.

Example with Shared Cases:


char grade = 'B';

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

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

#buttons=(Ok, Go it!) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Ok, Go it!