AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Mediumcshort circuit

~90s

Short-circuit evaluation

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;
}
Show the answer and the worked solution

Correct answer: B.

1 5

Worked solution

  1. a++ yields the old value 0, which C reads as false, and as a side effect a becomes 1.
  2. Because the left operand of && is false, the whole condition is already decided, so ++b is never evaluated and b stays 5.
  3. 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.

Short-circuit evaluation — Aptitude Question

Short-circuit evaluation: What does this C program print? Answer and worked solution on CodeKairo.

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

  1. 0 5
  2. 1 5
  3. 1 6
  4. 2 100
Show the answer and the worked solution

Correct answer: B. 1 5

Worked solution

  1. a++ yields the old value 0, which C reads as false, and as a side effect a becomes 1.
  2. Because the left operand of && is false, the whole condition is already decided, so ++b is never evaluated and b stays 5.
  3. 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