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

Discussion

What will be the output of the program?

#include <stdio.h>
#define CUBE(x) (x*x*x)

int main()
{
    int a, b=3;
    a = CUBE(b++);
    printf("%d, %d\n", a, b);
    return 0;
}

 

  • A.9, 4
  • B.27, 4
  • C.27, 6
  • D.Error

Answer: C

Correct answer: 27, 6

CUBE(b++) expands to (b++*b++*b++), which modifies b three times in one expression with no sequence point between - formally undefined behaviour. The listed answer, 27 and 6, is what the common compilers give: the three operands all read 3 before any increment takes effect, and b ends three higher. Nothing should rely on it; the real lesson is never to pass an argument with a side effect to a macro that uses it more than once.

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

Post your comment

Please log in or register to post a comment.