ProgrammingVery hardGATE CS

What is printed?

What is printed?
#include <stdio.h>
int f(int x) {
    int r = 0;
    switch (x) {
        case 1: r += 1;
        default: r += 10;
        case 2: r += 2; break;
        case 3: r += 3;
    }
    return r;
}
int main(void) {
    printf("%d %d %d %d", f(1), f(2), f(3), f(4));
    return 0;
}
  1. A. 11 2 3 10
  2. B. 1 2 3 12
  3. C. 13 2 6 12
  4. D. 13 2 3 12

Correct answer: D. 13 2 3 12

Without break, execution falls through: f(1) runs case 1, default and case 2 (1 + 10 + 2 = 13); f(2) adds 2 and breaks; f(3) adds 3 and leaves the switch; f(4) jumps to default, then falls into case 2: 10 + 2 = 12.

More C Programming questions

Exams that ask this topic