c - Macro result malfunction in an operation -
this question has answer here:
- the need parentheses in macros in c 8 answers
i tried macro:
#define min(x,y) x<y? x:y
it's supposed return minimum , does. problem when trying use result of macro in operation, doesn't work.
example
x=min(3,4);
here x naturally have 3 value, when trying this:
x= 23 + min(3,4);
the result still 3 (the result of macro), no matter number add (23 arbitrary in there). may know why happens?
the problem operator assocativity , precedence. when expand macro, becomes:
x = 23 + 3 < 4 ? 3 : 4;
which interpreted as:
x = (23 + 3) < 4 ? 3 : 4;
because arithmetic has higher precedence comparison operators. should wrap expansion in parentheses force treated single expression.
#define min(x,y) (x<y? x:y)
you should put parenthese around uses of each parameter, in case they're expressions operators have lower precedence <
.
#define min(x,y) ( (x) < (y) ? (x) : (y) )
but using macro function still bad idea. repetitions of parameters mean can't use expressions side effects. e.g. min(i++, j++)
increment 1 of variables twice. better use inline function.
Comments
Post a Comment