← 🔀 Control Flow & Output
Subtopic 3 of 4

2.3Short-circuit evaluation and ?:

The idea

&& and || stop as soon as the answer is known. The skipped operand is not executed at all, side effects included.

Think of it like this: If the first question already decides the quiz, the examiner never asks the second one.

Why it exists

A hidden i++ on the right of && is a favourite way to make a count differ from your first guess.

How it works

  1. Evaluate the left operand.
  2. For &&: if it is 0, the result is 0 and the right side is skipped. For ||: if it is non-zero, the result is 1 and the right side is skipped.
  3. Only otherwise evaluate the right side.
  4. ?: evaluates only the chosen branch; the comma operator evaluates both, left to right.

Worked example: (j >= 0) && (i++) for j = −3..3

For j = −3, −2, −1 the left side is false, so i++ never runs. At j = 0, i++ gives 0 (false) and i becomes 1. At j = 1, 2, 3, i++ gives 1, 2, 3 (true) so count adds 1, 2, 3. i ends at 4 and count = 6 + 4 = 10.

Now play with it

  • →Run && skips the side effect and watch i stay at 0 for the first three iterations.
  • →In the || skips too tab check that b++ only runs in the last statement.

For j below 0 the left side is false, so (i++) is never evaluated and i stays 0. i starts moving only when j reaches 0.

step 1 of 33
1#include <stdio.h>
2int main() {
3 int i, j, count;
4 count = 0;
5 i = 0;
6 for (j = -3; j <= 3; j++) {
7 if ((j >= 0) && (i++))
8 count = count + j;
9 }
10 count = count + i;
11 printf("%d", count);
12 return 0;
13}

The gold line is the statement about to run.

Call stack (top first)
main()
no variables yet
Output

Check yourself

int a = 0, b = 0; if (a++ && b++) {}. What are a and b afterwards?

Remember: && and || skip the right operand when the left decides the answer.
Exam notes (the dense version)

a && b does not evaluate b when a is 0; a || b does not evaluate b when a is non-zero. Side effects in b (such as i++) may never happen. The result is always 0 or 1. c ? x : y evaluates only one branch. The comma operator evaluates left to right and gives the last value.

Previous year questions: Control Flow & Output (10)

PYQs are grouped by topic, so this is the full set for Control Flow & Output; try the ones that match this subtopic. Open all 10 on the topic page.