The need for parentheses in macros in C [duplicate]
Pre-processor macros perform text-replacement before the code is compiled so
SQR(b+5)
translates to
(b+5*b+5) = (6b+5) = 6*3+5 = 23
Regular function calls would calculate the value of the parameter (b+3) before passing it to the function, but since a macro is pre-compiled replacement, the algebraic order of operations becomes very important.
Consider the macro replacement using this macro:
#define SQR(x) (x*x)
Using b+5
as the argument. Do the replacement yourself. In your code, SQR(b+5)
will become: (b+5*b+5)
, or (3+5*3+5)
. Now remember your operator precedence rules: *
before +
. So this is evaluated as: (3+15+5)
, or 23
.
The second version of the macro:
#define SQR(x) ((x) * (x))
Is correct, because you're using the parens to sheild your macro arguments from the effects of operator precedence.
This page explaining operator preference for C has a nice chart. Here's the relevant section of the C11 reference document.
The thing to remember here is that you should get in the habit of always shielding any arguments in your macros, using parens.
Because (3+5*3+5 == 23)
.
Whereas ((3+5)*(3+5)) == 64
.
The best way to do this is not to use a macro:
inline int SQR(int x) { return x*x; }
Or simply write x*x
.
The macro expands to
a = b+5*b+5;
i.e.
a = b + (5*b) + 5;
So 23.