ProgrammingVery hardProduct company OA

What is printed?

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

Correct answer: C. 2 4 2

Macros substitute text. MIN(next(), 5) becomes ((next()) < (5) ? (next()) : (5)): the first call (1) is only compared; the selected operand calls next() AGAIN, so a = 2 and calls = 2 (well defined – ?: has a sequence point). SQ has no parentheses: a + 1 * a + 1 / 2 * 2 = 2 + 2 + 0 = 4, because 1 / 2 is 0 in integer division. '2 2 2' assumes SQ(a + 1) / SQ(2) = 9 / 4.

More C Programming questions

Exams that ask this topic