0
0
Cprogramming~10 mins

Switch statement - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Switch statement
Start
Evaluate expression
Match case?
NoDefault case?
Execute case
Break?
NoContinue next case
Yes
Exit switch
The switch statement evaluates an expression, matches it to a case, executes that case's code, and exits or continues based on break statements.
Execution Sample
C
int x = 2;
switch (x) {
  case 1:
    printf("One\n");
    break;
  case 2:
    printf("Two\n");
    break;
  default:
    printf("Other\n");
}
This code checks the value of x and prints the matching case text.
Execution Table
StepExpression ValueCase CheckedMatch?ActionOutput
12case 1NoSkip case 1
22case 2YesExecute case 2 codeTwo
32breakN/AExit switch
💡 Break statement after case 2 causes exit from switch.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
x2222
Key Moments - 2 Insights
Why does the switch stop after printing "Two"?
Because of the break statement at step 3 in the execution_table, which exits the switch to prevent running other cases.
What happens if there is no break after a case?
The switch continues to execute the next case(s) until it finds a break or reaches the end, as shown by the 'Continue next case' path in the concept_flow.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output at step 2?
AOne
BTwo
COther
DNo output
💡 Hint
Check the 'Output' column at step 2 in the execution_table.
At which step does the switch statement exit?
AStep 1
BStep 2
CStep 3
DIt never exits
💡 Hint
Look at the 'Action' column and see when 'Exit switch' happens.
If the break at step 3 was removed, what would happen?
AOnly case 2 runs
BDefault case runs after case 2
CProgram crashes
DNo output at all
💡 Hint
Refer to the concept_flow where 'No break' leads to 'Continue next case'.
Concept Snapshot
switch(expression) {
  case value1:
    // code
    break;
  case value2:
    // code
    break;
  default:
    // code
}

- Evaluates expression once
- Matches cases in order
- Executes matching case
- break exits switch
- Without break, runs next cases
Full Transcript
The switch statement in C evaluates an expression and compares it to each case value. If a match is found, it executes that case's code. The break statement stops further case execution and exits the switch. Without break, execution continues to the next case. If no case matches, the default case runs if present. This example shows x=2 matching case 2, printing 'Two', then breaking to exit.