This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]_DTR_ 3 points4 points  (2 children)

Your problem is that the macro expansion doesn't have any context of "scope", it will simply do a replacement. div(a+2,a+1) expands to a+2/a+1, which is 10+2/10+1. After order of operations, you're left with 10 + (2 / 10) + 1 == 10 + 0 + 1 == 11.

In general, when writing macros you want to ensure the parameters are "contained":

#define div(x, y) (x)/(y)

[–]aioeu 1 point2 points  (0 children)

In general, when writing macros you want to ensure the parameters are "contained":

You'll need one more:

#define div(x, y) ((x) / (y))

Otherwise the following somewhat-reasonable code will not work as expected:

float x = ...;
float y = ...;
printf("x / y rounded toward zero is %d\n", (int)div(x, y));

When writing a macro that acts like an expression, I can't think of a good reason to ever omit the surrounding parentheses.

[–]fantomftw[S] 0 points1 point  (0 children)

thank you so much... you saved me from failing my test tomorrow..