C Switch

Learn 'switch' case statement in C.

Switch Case:

A 'switch' statement in C is a control structure that allows you to select one of several code blocks to execute based on the value of an expression. It provides a way to simplify code that involves multiple 'if-else' conditions when you have a single expression to evaluate against multiple possible values.

The basic syntax of a switch statement in C looks like this:

switch (expression) {
    case value1:
        // Code to execute if expression equals value1
        break;

    case value2:
        // Code to execute if expression equals value2
        break;

    // More cases as needed

    default:
        // Code to execute if expression doesn't match any case
}

How it works?

1. The 'expression' inside the 'switch' statement is evaluated.

2. The 'case' labels represent the possible values that the 'expression' can take. If the 'expression' matches one of the 'case' values, the corresponding block of code is executed.

3. The 'break' statement is used to exit the 'switch' block once a 'case' is matched. Without break, execution will continue to the next 'case' block and subsequent ones, even if they don't match the 'expression'.

4. The 'default' case is optional and is executed if none of the 'case' values match the 'expression'. It acts as a catch-all case.

Here's an example:

c Copy Code
#include <stdio.h>

int main() {
    int choice = 2;

    switch (choice) {
        case 1:
            printf("You chose option 1\n");
            break;

        case 2:
            printf("You chose option 2\n");
            break;

        case 3:
            printf("You chose option 3\n");
            break;

        default:
            printf("Invalid choice\n");
    }

    return 0;
}
Output:
You chose option 2

In this example, if 'choice' is 2, it will print "You chose option 2". If 'choice' is any other value, it will print "Invalid choice" because there's no matching 'case'.

Note: C allows the use of 'switch' with various data types, including integers, characters, and enumerations. Each 'case' label must have a constant value of the same data type as the 'expression'.

char choice = 'A'; // case 'A':

What is New?

We have just updated this website & still working on adding new content & updating existing features.