In the web, I read that to define a macro that behave like a function, the syntax is:
#define foo(x,y) (bar((x),(y)))
but considering that a macro is just text replacement, why is the syntax above used, and not just (bar(x,y)) or bar(x,y)?
If I write
#define add0(x,y) ((x)+(y))
#define add1(x,y) (x+y)
#define add2(x,y) x+y
All of the three macros output 3 when printed.
Writing without parentheses can lead to unexpected operator precedence problems.
Consider the following example:
If you call add2(1, 2) * 3, it would expand to 1 + 2 * 3, which is 7, not 9. This is because the multiplication operator has higher precedence than the addition operator in C and C++.
However, if you define the macro as:
It's fine now.