Short-circuit evaluation — Aptitude Question
Short-circuit evaluation: What does this C program print? Answer and worked solution on CodeKairo.
- Topic: Programming Fundamentals
- Section: Programming MCQs
- Difficulty: Medium
- Time target: 90 seconds
Question
What does this C program print?
#include <stdio.h>
int main(void) {
int a = 0, b = 5;
if (a++ && ++b) {
b = 100;
}
printf("%d %d", a, b);
return 0;
}Options
- 0 5
- 1 5
- 1 6
- 2 100
Show the answer and the worked solution
Correct answer: B. 1 5
Worked solution
- a++ yields the old value 0, which C reads as false, and as a side effect a becomes 1.
- Because the left operand of && is false, the whole condition is already decided, so ++b is never evaluated and b stays 5.
- The if body does not run, so b is not set to 100 and the program prints 1 5.
Answer: 1 5.
The idea
&& stops as soon as the result is known, so side effects in the right operand may never happen. The side effect in the left operand happens regardless, which is what separates 1 5 from 0 5.
Shortcut. a++ yields 0, so && is settled by its left side: ++b and b = 100 never run, but a's own increment still happens, giving 1 5.
Common trap. "1 6" evaluates both operands as a non-short-circuit & would, bumping b to 6 even though the result was already false.
All Programming Fundamentals questions · placement mock tests