The switch statement enables us to choose one course of action from a set of possible actions based on the evaluation of an expression.
int num = 8;
printf("The number is four.\n");
printf("The number is six.\n");
printf("The number is eight.\n");
As we have seen above, the value of the expression in parentheses following the keyword switch determines which of the statements between the braces will be executed.
The break statement causes switch to skip over the other statements within that block and continue with whatever statement follows the closing brace. If we do not put a break statement in, then a switch statement can end up giving us multiple results. Sometimes, that’s a good thing, and sometimes, that’s a bad thing.
int a = 16;
printf("a == 15\n");
printf("a == 16\n");
printf("a == 17\n");
We can associate several case values with one group of statements.
printf("Enter a letter:\n");
printf("The character is a vowel.");
printf("The character is a number.");
printf("The character is a consonant.");
Note that placing a break statement after the default case is not, strictly speaking, necessary.
If you have an Amazon Kindle or Kindle app, take a look at my book on C:
As well as my book on Linux: