The need for parentheses in macros in C

Kushal picture Kushal · May 30, 2012 · Viewed 27.3k times · Source

I tried to play with the definition of the macro SQR in the following code:

#define SQR(x) (x*x)
int main()
{
    int a, b=3;
    a = SQR(b+5);      // Ideally should be replaced with (3+5*5+3), though not sure.
    printf("%d\n",a);
    return 0;
}

It prints 23. If I change the macro definition to SQR(x) ((x)*(x)) then the output is as expected, 64. I know that a call to a macro in C replaces the call with the definition of the macro, but I still can’t understand, how it calculated 23.

Answer

Babak Naffas picture Babak Naffas · May 30, 2012

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.