ProgrammingVery hardProduct company OA

What is printed?

What is printed?
#define MIN(a, b) ((a) < (b) ? (a) : (b))
int calls = 0;
int next(void) { calls++; return calls; }
int main(void) {
    int r = MIN(next(), next());
    printf("%d %d", r, calls);
}
  1. A. 1 2
  2. B. 3 3
  3. C. 1 3
  4. D. 2 3

Correct answer: B. 3 3

MIN(next(), next()) expands to ((next()) < (next()) ? (next()) : (next())): the condition evaluates next() twice (giving 1 and 2 in some unspecified order), and whichever branch the ternary then picks calls next() a THIRD time for its value. So r is always the third call's return value, 3, and calls ends at 3 regardless of which operand of < was evaluated first.

More C Programming questions

Exams that ask this topic