switch

Case Distinctions

Problem: if - else if … - else

  • Much typing

  • … especially when checking for equality of integers

  • Direct jump table (compiler generated) would be more efficient

if - else if vs. switch

if (c == ' ')
    ...
else if (c == '\n' ||
         c == '\t')
    ...
else
    ...
switch (c) {
    case ' ':
        ...
        break;
    case '\n':
    case '\t':
        ...
        break;
    default:
        ...
}

switch

  • Labels must only be constants (and constant expressions), no variables

    • known at compile time

  • Equality ⟶ code starting at label is executed, until the end of switch statement

  • break: fall through otherwise

  • fall through sometimes desired, but mostly not ⟶ careful!

  • default label is optional

When do I use it?

  • Finite number of values (e.g. states of a state machines)

  • switch over enum without default: compiler can warn about missing label ⟶ very useful!