O'Reilly logo

C Programming: Visual Quickstart Guide by Marc Liyanage, Larry Ullman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required