Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will be the output of the program?

#include <stdio.h>
#define MAN(x, y) ((x)>(y)) ? (x):(y);

int main()
{
    int i=10, j=5, k=0;
    k = MAN(++i, j++);
    printf("%d, %d, %d\n", i, j, k);
    return 0;
}

 

  • A.12, 6, 12
  • B.11, 5, 11
  • C.11, 5, Garbage
  • D.12, 6, Garbage

Answer: A

Correct answer: 12, 6, 12

The macro has no protection against multiple evaluation, so the arguments are substituted textually:

k = ((++i)>(j++)) ? (++i):(j++);

The condition increments i to 11 and yields j’s old value 5, leaving j at 6. Since \(11 > 5\), the true branch runs and increments i again, to 12, which is what k receives. Output: 12, 6, 12 - and i was incremented twice for a single-looking macro call, which is the danger the question illustrates.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.