I'm learning C, but I do not understand this:
#define square(x) x*x
a = square(2+3) //a = 11
When this is run, why does a
end up being 11
?
I'm learning C, but I do not understand this:
#define square(x) x*x
a = square(2+3) //a = 11
When this is run, why does a
end up being 11
?
square(2+3)
expands to2+3*2+3
which is equivalent to2+(3*2)+3
[*
has higher precedence than+
]On gcc you can use
-E
option to see what your preprocessor generatesRemedy
Try this
It expands to
2+3*2+3
, which is equivalent to2+(3*2)+3
. Use parentheses to fix it:Now try it with
square(x++)
and you'll run into more problems (undefined behavior). Avoid doing this as a macro if you can.think about what you get when the macro is expanded. The c preprocessor will expand this as
You need to correctly define your macro. Always enclose the macro variable in parenthesis. This would give you the expected result.
The macro expansion would be this:
Because
2 + 3
is substituted literally in the expressionx * x
, it becomes2 + 3 * 2 + 3
, and the*
operator has a higher precedence so you don't get the expected result.Always enclose macro arguments and the whole expression in parentheses to avoid this:
Also note that any expression you pass will be evaluated twice, and that can be undesired if the expression has a side effect such as an assignment, or a function call. In these cases it is better to use an inline function.
Try: