ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
int x = 5;
int y = x++ + (x = 10);
printf("%d", y);
  1. A. 15, deterministically
  2. B. 20, deterministically
  3. C. Undefined behaviour: x is modified by both x++ and the assignment within the same expression, unsequenced relative to each other
  4. D. 10

Correct answer: C. Undefined behaviour: x is modified by both x++ and the assignment within the same expression, unsequenced relative to each other

Both x++ (a side effect) and (x = 10) (another side effect) modify the same object x within one full expression, with the addition operator providing no sequencing guarantee between evaluating its two operands. Two unsequenced writes to the same scalar object is undefined behaviour in C, regardless of what any given compiler prints.

More C Programming questions

Exams that ask this topic