Possible Duplicate:
square of a number being defined using #define
Can you please explain why the following code outputs "29"?
#define Square(x) (x*(x))
void main()
{
int x = 5;
printf("%d", Square(x+3));
}
Since macros only do textual replacement you end up with:
x + 3 * (x + 3)
which is 29.
You should absolutely always put macro arguments between parentheses.
#define Square(x) ((x)*(x))
Better yet, use a function and trust the compiler to inline it.
EDIT
As leemes notes, the fact that the macro evaluates x
twice can be a problem. Using a function or more complicated mechanisms such as gcc statement expressions can solve this. Here's a clumsy attempt:
#define Square(x) ({ \
typeof(x) y = (x); \
y*y; \
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With