Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

How does Switch work in C++?

+11 votes
asked May 7 by Melina Donut (220 points)

3 Answers

0 votes
answered May 7 by Nishan Nahsin (140 points)
choose one of many code path it based on the value of variable or expression
0 votes
answered May 11 by Peter Minarik (101,340 points)
0 votes
answered May 13 by Zach (380 points)
You would use it to check the value of a specific variable or expression against a bunch of values, and execute specific code based on it. For example:

#include <stdio.h>

int main() {
    int rating;
    
    printf("How do you feel today on a scale of 1 to 5? "); // just as an example
    scanf("%d", &rating); // getting user input
    
    switch (rating) {
        case 1:
            printf("I'm sorry to hear that!");
            break; // important because it tells the computer to stop looking for values
            // otherwise you might run code from the next branches by accident
        case 2:
            printf("What happened?");
            break;
        // etc ...
        // repeat for as many values as you need
        default: // if no values were matched, then run what's in this block
            printf("I don't think %d is within the range of 1 to 5!", rating);
            break;
    }

    return 0;
}

Oftentimes, switches are used to clean up clutter, as the above switch statement looks much cleaner than

if (rating == 1) ...
else if (rating == 2) ...
...
else ...

It's also considered better practice.

Just note that it only works on primitive types, like int and char, so things like std::string or std::vector<...> won't work.
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and receive answers from other members of the community.
...