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.