C Programming Basics

int n = 2, c = 0;
switch (n) {
case 1: c += 1;
case 2: c += 10;
case 3: c += 100; break;
default: c += 1000;
}
printf("%d\n", c);

Which of the following is the output when the switch statement above, which contains a case without break, is executed?

  1. A10
  2. B110
  3. C1110
Show answer and explanation

Answer: B. 110

A switch statement jumps to the case label matching the value of n and from there keeps executing the statements of the following cases until it meets a break (fall-through). n is 2, so execution starts at case 2, and after c += 10 it also executes c += 100 of case 3, then leaves the switch at break. c is 10 + 100 = 110. When falling through is intended, saying so in a comment makes it easy to tell apart from a forgotten break.

  • A. There is no break after case 2, so the statement of case 3 is also executed.
  • B. Correct. case 2 and case 3 run in sequence, and break leaves the switch.
  • C. The break after case 3 leaves the switch, so the default statement is not executed.
Practice this topic Back to topic

Books on C Programming Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More C Programming Basics questions

  1. Which of the following is the output when the program above is executed?
  2. When the function f above is called three times in a row, which of the following is the return value of the third call?
  3. In C, which of the following correctly pairs the lifetimes of (1) a local variable declared inside a function without static, (2) a region allocated with malloc, and (3) a variable declared outside any function?
  4. int is 32 bits (maximum 2147483647). Which of the following is the largest n for which the function fact(n) above returns the factorial of n correctly, without overflow?
  5. int is 4 bytes and pointers are 8 bytes. When the value (address) of a pointer to int p is 0x1000, which of the following is the value of p + 3?