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));
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Since macros only do textual replacement you end up with:
which is 29.
You should absolutely always put macro arguments between parentheses.
Better yet, use a function and trust the compiler to inline it.
EDIT
As leemes notes, the fact that the macro evaluates
xtwice can be a problem. Using a function or more complicated mechanisms such as gcc statement expressions can solve this. Here’s a clumsy attempt: