Labs ICT
โญ Pro Login

Switch

The switch Statement

When you have one value to match against many possibilities, switch is cleaner than a long chain of else if.

int day = 3;

switch (day) {
  case 1:
    cout << "Monday";
    break;
  case 2:
    cout << "Tuesday";
    break;
  case 3:
    cout << "Wednesday";
    break;
  default:
    cout << "Unknown";
}

break and default

Each case needs a break to stop execution from falling through to the next case. The default case runs when no other case matches. It usually goes at the end.

Without break, execution keeps going into the next case โ€” sometimes useful, but often a bug.

Try it Yourself โ†’

๐Ÿงช Quick Quiz

What keyword stops fall-through in a switch statement?