[Solved] Incorrect answer from #define SQR(x) (x*x) [duplicate]


Read the wikipage about the C preprocessor and understand that the C preprocessor operate at a purely textual level (as the first phase of the compiler). Read also GNU cpp documentation. Your y = SQR(++x);is expanded as

y = ++x * ++x;

Which is not what you should want. Read about undefined behavior (and this answer).
Think about the horror happening (using your original SQR) with SQR(y+3).

Look at the preprocessed form of your source code. With GCC, use

gcc -C -E foo.c > foo.i

to obtain into foo.i (which you should examine with an editor or a pager) the preprocessed form of foo.c

So, at the very least, you should define your macro as

#define SQR(x) ((x)*(x))

Otherwise SQR(y+3) won’t be expanded like you want. In general when using a macro you should know (and document, e.g. in a comment, if you are writing the macro) what is happening.

In fact, in your case, you should not use a macro at all, but define an inline function

static inline int square(int x) { return x*x; }

this would be as fast as your macro, but much more safe, since square(++x) would increment (rightly) x only once, and square(y+3) is doing what you want!

0

solved Incorrect answer from #define SQR(x) (x*x) [duplicate]