-5

The following program is printing 49

#include <stdio.h> 
#define SQR(x) (x*x) 
void main(void) { 
    int x, y; x = 5; 
    y = SQR(++x); 
    printf("y is %d\n", y); 
}

I don't understand what I am missing.
Here is what I am understanding how it might be working
In SQR(++x), ++x will be evaluated to be 6 and after x*x the 36 should be returned.
Therefore y = 36
But the answer is 49

afzalex
  • 8,598
  • 2
  • 34
  • 61

2 Answers2

5

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!

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
2

Remember that macros are replaced pretty much verbatim, that means your

SQR(++x);

will be replaced by

++x * ++x;

And, as noted by dyp, it's undefined behavior.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621