When I define this macro:
#define SQR(x) x*x
Let’s say this expression:
SQR(a+b)
This expression will be replaced by the macro and looks like:
a+b*a+b
But, if I put a ++ operator before the expression:
++SQR(a+b)
What the expression looks like now? Is this ++ placed befor every part of SQR paramete? Like this:
++a+b*++a+b
Here I give a simple program:
#define SQR(x) x*x
int a, k = 3;
a = SQR(k+1) // 7
a = ++SQR(k+1) //9
When defining macros, you basically always want to put the macro parameters in parens to prevent the kind of weird behaviour in your first example, and put the result in parens so it can be safely used without side-effects. Using
makes
SQR(a+b)expand to((a+b)*(a+b))which would be mathematically correct (unlikea+b*a+b, which is equal to ab+a+b).Putting things before or after a macro won’t enter the macro. So
++SQR(x)becomes++x*xin your example.Note the following:
You’re seeing the
++SQR(a+b)appear to increment by 2 since the preincrement kicks in beforeai read either time, i.e.aincrements, then is used twice and so the result is 2 higher than expected.NOTE As @JonathanLeffler points out, the latter call invokes undefined behaviour; the evaluation is not guaranteed to happen left-to-right. It might produce different results on different compilers/OSes, and thus should never be relied on.