GATE Computer ScienceModerateGATE CS (PYQ pattern)

int f(void) { static int c = 0; return ++c; } int main() { int x = f() || f(); int y = f() && f() > 3 ? f() : -f(); printf("%d %d %d", x, y, f()); } What is printed?

  1. A. 1 5 6
  2. B. 1 1 5
  3. C. 1 -3 4
  4. D. 1 -4 5

Correct answer: D. 1 -4 5

|| and && evaluate left to right with a sequence point and short-circuit, and ?: evaluates its condition first, so every call order here is fixed. x: the first f() returns 1, so the right side is skipped; x = 1. y parses as (f() && (f() > 3)) ? f() : -f(): f() = 2 is true, f() = 3 > 3 is false, so the else branch runs, y = -f() = -4. The last call returns 5. Calling the skipped f() in x would give 1 5 6; grouping ?: inside && gives 1 1 5.

More Programming and Data Structures (GATE) questions

Exams that ask this topic