Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#define Square(x) (x*(x)) [duplicate]

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));
}
like image 426
Dan Dinu Avatar asked Nov 27 '22 22:11

Dan Dinu


1 Answers

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;                \
})
like image 58
cnicutar Avatar answered Nov 29 '22 11:11

cnicutar