c - Weird result from a macro while using pre-increment and post-increment operators -
this question has answer here:
i 12 , 49 code
#include <stdio.h> #define product(a) a*a int main() { int = 3, j, k; j = product(i++); k = product(++i); printf("%d %d\n", j, k); return 0; } if instead of using macro use function 9 , 25, expect...
can explain why happen?
if expand macro, line
j = product(i++); becomes
j = i++*i++; and line
k = product(++i); becomes
k = ++i*++i; both these lines subject undefined behavior. can try make sense of 1 run of program results not guaranteed same different compiler or same compiler different compiler flags.
when use function call instead of macro, behavior of code more straight forward. line
j = product(i++); is equivalent to:
int temp = i; j = product(temp); i++; the line
k = product(++i); is equivalent to:
++i; k = product(i); hence, there no problems when function used instead of macro.
Comments
Post a Comment