c - Macro Substitution assignment -
#define max(x,y)(x)>(y)?(x):(y) main() {     int i=10,j=5,k=0;     k==max(i++,++j);     printf("%d %d %d",i,j,k);//11 7 0 } why output 11 7 0 instead of 11 6 0?
the statement expands to
k==(i++)>(++j)?(i++):(++j) let's re-write added parens emphasise how expression parsed when accounting precedence rules:
( k == ( (i++) > (++j) ) ) ? (i++) : (++j) note > has higher precedence ==. 
now, (i++) > (++j) evaluated first, evaluates 1 , both i , j incremented. k compared equality 1 , yields 0. conditional operator evaluates (++j) , j incremented 1 more time. 
in total i incremented once, j incremented twice , k not modified. , hence output describe.
this example of perils of using macros. function need.
some other points:
- your maindeclared incorrectly. shouldint main(void).
- if compile warnings enabled compiler flag line in question. compiler says:
c:\users\blah\desktop>gcc main.c -wall -o main.exe main.c: in function 'main': main.c:2:20: warning: suggest parentheses around comparison in operand of '==' [-wparentheses] #define max(x,y)(x)>(y)?(x):(y) ^ main.c:6:8: note: in expansion of macro 'max' k==max(i++,++j); ^
Comments
Post a Comment