liveBook · Manning

Case statement

As explained in Modern C, Third Edition

A switch statement is a C selection statement that transfers control to a matching case or default label based on an expression's value.

A case statement is C’s multiple-selection construct. It evaluates the switch expression, transfers control to the matching case label, or selects default when no case matches. Case and default labels act as jump targets inside the secondary block. section 3.0 section 3.3

Selecting among character values

switch (arg) { case 'm': puts("this is a magpie"); break; case 'r': puts("this is a raven"); break; case 'j': puts("this is a jay"); break; case 'c': puts("this is a chough"); break; default: puts("this is an unknown corvid"); } Each break terminates the enclosing switch and transfers control to the following statement. Without break, execution continues into subsequent cases. section 3.3

Use case labels within these constraints:

  • Make every case value an integer constant expression; variables belong in the switch expression, not as case values. section 3.3
  • Keep case values unique within one switch statement. section 3.3
  • Treat fall-through deliberately: execution continues until break or the end of the secondary block. section 3.3 section 3.4
  • Guard declarations carefully inside the block, because a jump directly to a case can leave a variable uninitialized. section 3.3
switch (count) {
  default:puts("++++ ..... +++");
  case 4: puts("++++");
  case 3: puts("+++");
  case 2: puts("++");
  case 1: puts("+");
  case 0:              // prior to C23 this needed an extra ``;"
}

Shows intentional fall-through by selecting a count and then running the matching and subsequent case bodies. section 3.3

How Modern C, Third Edition covers it

How deep it goes
Explains selection, jump targets, fall-through, constraints, and declaration hazards, while deferring broader control-flow mechanics.
Examples
Uses corvid selection, a count-generated triangle, and character dispatch in a recursive code-indentation parser.
What it assumes
Assumes familiarity with C statements and expressions while defining selection, labels, jump targets, and break behavior.
What you can do after
Apply switch statements with deliberate fall-through, unique constant cases, default handling, and correctly terminated branches.
How it connects
Connects switch statements with if-else selection, break statements, integer constant expressions, and jump-based control flow.

Also explained in

Compare how 9 books explain case statement →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.