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. */
        break;
   case 2004:
        /* Do something else. */
        break;
   default:
        /* Do this. */
        break;
}

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 O’Reilly online learning.

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