c++cmacrosc-preprocessor

C preprocessors and order of operations


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?


Solution

  • It expands to 2+3*2+3, which is equivalent to 2+(3*2)+3. Use parentheses to fix it:

    #define square(x) ((x)*(x))
    

    Now try it with square(x++) and you'll run into more problems (undefined behavior). Avoid doing this as a macro if you can.