HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

C Switch



Switch Statement


In C programming, a switch statement is a control flow structure used to execute different blocks of code based on the value of a single variable or expression. It's a more efficient and readable alternative to using multiple if-else statements for several conditions.

The switch statement selects one of many code blocks to be executed:

Syntax

switch (expression) {

case x:

// code block

break;

case y:

// code block

break;

default:

// code block

}


This is how it works:

  • expression: This is an integer or character variable or expression that is evaluated and compared with the case values.
  • case values: Each case statement represents a possible value the expression might have.
  • code: The code blocks associated with each case are executed if the corresponding value matches the expression.
  • break: This statement is optional and exits the switch block after the matched case code is executed. If omitted, code execution continues to the next case even if it doesn't match.
  • default: This is an optional block that executes if none of the case values match the expression.
  • Example

    #include <stdio.h>

    int main() {

    int day = 4;


    switch (day) {

    case 1:

    printf("Monday");

    break;

    case 2:

    printf("Tuesday");

    break;

    case 3:

    printf("Wednesday");

    break;

    case 4:

    printf("Thursday");

    break;

    case 5:

    printf("Friday");

    break;

    case 6:

    printf("Saturday");

    break;

    case 7:

    printf("Sunday");

    break;

    }

    return 0;

    }


    Output

    Thursday


    The break Keyword


    1 - Loop break: Used within loops (like for, while, or do-while) to terminate the loop prematurely.


    2 - Switch break: Used within a switch statement to exit the switch block prematurely.


    A break can save a lot of execution time because it "ignores" the execution of all the rest of the code in the switch block.


    The default Keyword

    The default keyword specifies some code to run if there is no case match:


    Example

    #include <stdio.h>

    int main() {

    int day = 4;


    switch (day) {

    case 6:

    printf("Today is Saturday");

    break;

    case 7:

    printf("Today is Sunday");

    break;

    default:

    printf("Looking forward to the Weekend");

    }

    return 0;

    }


    Output

    Looking forward to the Weekend


    Note: The default keyword must be used as the last statement in the switch, and it does not need a break.