Concepts / Switch Statements in C++

Switch Statements in C++

A switch statement compares one value against a set of case labels.

  • Programming

Predicting a Switch Before Reading About It

This article starts with a program rather than a definition. The program combines two ideas you have already met: a switch statement that includes a default case, and a loop that repeatedly updates the state of a game or simulation. Before reading the explanation, make a prediction about what the switch prints. Watching which line runs first, which runs next, and what each line leaves behind matters more than the final output alone.

What do you think happens?

The variable command holds the value 4. None of the case labels is 1 or 2. What does the switch print?

  • Move left

  • Move right

  • Unknown command

  • Nothing is printed

Reveal answer
Answer:

Unknown command

No case label matches 4, so control moves to the default label, and the default body prints Unknown command. The default case exists to catch exactly this kind of unmatched value.

Tracing a Game Update Loop

A game or simulation update loop repeatedly changes the state of the program and then shows that state to the user. Two actions happen in this kind of loop. The first is a move step, which moves an object based on a delta and a scale: the new position is the current position plus delta times scale. The second is an update step, which redraws the screen so the new position is visible. The example below keeps only the move step and prints the position after each pass, so the state is easy to follow.

cpp
Output
Pass 1: position = 6
Pass 2: position = 12
Pass 3: position = 18
Notes on the code
  • position starts at 0 before the loop begins
  • delta * scale is 2 * 3, which is 6 on every pass
  • each pass starts with the position left behind by the previous pass

Read the loop as a sequence of passes. Pass 1 begins with position 0 and ends with position 6. Pass 2 does not start from 0; it starts from the 6 left by pass 1, so it ends with 12. Pass 3 starts from 12 and ends with 18. Tracing a loop means writing down the state at the start of each pass, applying the statements in order, and recording the state at the end. The table below does that for this program.

Passposition beforedelta times scaleposition afterPrinted line
1066Pass 1: position = 6
26612Pass 2: position = 12
312618Pass 3: position = 18

Trace of the update loop, one row per pass

position 0before pass 1position 6after pass 1position 12after pass 2position 18after pass 3pass 1 adds 6pass 2 adds 6pass 3 adds 6
After each pass, what is the value of position, and how does that value feed into the next pass?
pass <= 3?check before the bodymove stepposition + delta * scaleprint positionupdate the display++passadvance the counterloop endspass is 4yesthenthenback to topno
On each pass, which statement runs first, which runs next, and how does control return to the top of the loop?

The diagram shows one pass, but the program returns to the start of the body again and again. Each return begins with the state the previous pass left behind. That is why a small error in the move step does not stay small: it carries forward into every later pass.

When the Default Case Runs

Definition

The default case of a switch statement specifies the actions to take for unexpected or unmatched values, meaning values that no explicit case label handles.

A switch statement compares one value against a set of case labels. When a label matches, the body under that label runs. The default label is the fallback. It is reached only when the switch value matches none of the explicit cases. Its purpose is to catch input that none of the explicit cases were written to handle, so the program does not silently skip that situation. The example below uses a value that no case matches, so the default body runs.

cpp
Output
Unknown command
Notes on the code
  • the switch value is 4
  • the label case 1 does not match 4
  • the label case 2 does not match 4
  • control reaches default, which prints the message
switch(command)command is 4case 1 matches?4 is not 1case 2 matches?4 is not 2Unknown commanddefault bodynext statementafter the switchMove leftcase 1 bodyMove rightcase 2 bodycompareyesnoyesnothen
When the switch value matches no case label, which path does control take to reach default, and where does execution go afterward?

Locating Where a Trace Departs

Tracing is most useful when the result is wrong. Suppose the move step is accidentally written without the scale. The loop still runs three passes and still prints lines, so the program looks healthy at a glance. The way to find the fault is to line up the expected trace against the actual trace, pass by pass, and stop at the first row where they differ. That row is where the result departs from expectation.

cpp
Output
Pass 1: position = 2
Pass 2: position = 4
Pass 3: position = 6
Notes on the code
  • the scale variable is declared but never used in the move step
  • the output looks plausible, so the trace must be compared against the expected values
PassExpected positionActual positionMatches?
162No, first divergence
2124No, error carried forward
3186No, error carried forward

Expected trace compared with the actual trace, pass by pass

The first row where the two columns disagree is pass 1. Nothing earlier diverged, because the loop starts at position 0 in both versions. The cause is the move step: the expected move adds delta times scale, which is 6, while the actual move adds only delta, which is 2. Every later pass inherits the wrong starting position, so the later rows differ as well. Finding the first divergence points you to the single statement that caused it, rather than to the whole loop.

Common Mistakes When Tracing

  • Common mistake

    Judging the program only by its final output

    What it looks like

    Looking only at Pass 3: position = 6 and deciding the loop is correct.

    Why it fails

    The final value alone does not show where the state went wrong, and a wrong trace can still look plausible.

    Do this instead

    Write the state at the start and end of each pass, and compare each pass with the expected value.

  • Common mistake

    Assuming each pass starts from the initial value

    What it looks like

    Believing pass 2 starts again from position 0.

    Why it fails

    Each pass begins with the state left by the previous pass, so position accumulates.

    Do this instead

    Carry the value from the end of one pass into the beginning of the next.

  • Common mistake

    Expecting default to run when a case matches

    What it looks like

    Setting command to 1 and expecting Unknown command to print.

    Why it fails

    The default body runs only when no explicit case label matches the switch value.

    Do this instead

    Check which case label matches first; default is reached only when none does.

  • Common mistake

    Guessing which statements belong to the loop

    What it looks like

    Reading a closing brace as ending the loop body when a nested block is still open.

    Why it fails

    The source emphasizes that brace pairing decides which statements belong to a loop, so a misread brace changes the trace.

    Do this instead

    Match each opening brace with its closing brace before deciding what runs on each pass.

Practice Tracing the Update Loop

EASY

Using the first update loop above, where delta is 2 and scale is 3 and position starts at 0, write the value of position at the end of each of the three passes. Then change the loop to run four passes and predict the fourth value before checking your answer.

Hints
  • Each pass adds delta times scale to the value left by the previous pass.
  • Write the value before each pass in one column and the value after in another.
  • The fourth pass should continue the same pattern, not restart from 0.

Key Takeaways

  • The default case of a switch runs only when no explicit case label matches the switch value, so it catches unmatched or unexpected input.
  • A game or simulation update loop repeatedly moves state and refreshes the display, and each pass begins with the state left by the previous pass.
  • Trace state pass by pass, writing the value before and after each pass, so you can see the order in which statements execute.
  • Compare the expected trace with the actual trace row by row; the first row where they differ points to the statement that caused the divergence.
  • Check brace pairing before deciding which statements belong to a loop, because a misread brace changes what the trace shows.

More concepts starting with S