The Switch Conditional

Along with the ternary operator, the switch is a useful variation on an if conditional. This conditional takes an integer variable as its condition and checks its value against several possibilities:

switch (year) {
   case 2005:
        /* Do something. */
   case 2004:
        /* Do something else. */
        /* Do this. */

The break statement is critical to the operation of the conditional. Upon hitting a break, the application will leave the switch. If you omit a break, then every subsequent statement—even those that fall under other cases—will be executed.

The default case is an optional one but, if included, is normally placed last. If none of the other cases are matched, the default case will be applied (like ...

Get C Programming: Visual Quickstart Guide now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.