Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

macro unsafe?

Status
Not open for further replies.

spiderling66

Programmer
Aug 21, 2004
5
0
0
GB
hi guys.

i hava no idea why the macro is unsafe, i just want the number(x) is always positive. could anyone tell me why, please?

#define number(x) x < 0 ? -x : x
 
Try various things like
Code:
y = number( x & 1 );
y = number( x++ );
y = number( printf("hello") );
Macros are very tricky to write which are safe against operator precedence and multiple evaluation, especially when there are side effects involved.

Fix operator precedence by putting everything in ()
Code:
#define number(x) ((x) < 0 ? -(x) : (x))

--
 
Code:
#define number(x) x < 0 ? -x : x

result = 6 + number(4 == 5) * 3;
is equivalent to
Code:
result = 6 + 4 < 0 ? -4 : 4 * 3;

Code:
]#define number(x) ((x) < 0 ? -(x) : (x))

result = 6 + number(4 == 5) * 3;
is equivalent to
Code:
result = 6 + ((4) < 0 ? -(4) : (4)) * 3;

Those have different meanings. The second one is more predictable from looking at the unexpanded macro call.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top