-
macro function result
I'm looking your expertise to help me understand why the output is not as expected.
Code:
#include <stdio.h>
#define SQUARE(x) (x)*(x)
int main()
{
printf("%d ", SQUARE(4)); // 16
int x = 3; // x = 3
printf("%d ", SQUARE(++x)); // Expecting 16 but getting 25
return 0;
}
Why program give value 25 instead of 16
-
This is what the compiler sees after the pre-processor has done it's evil thing.
Code:
$ gcc -E foo.c | tail
int main()
{
printf("%d ", (4)*(4));
int x = 3;
printf("%d ", (++x)*(++x));
return 0;
}
This is what the compiler thinks about it.
Code:
$ gcc -Wall foo.c
foo.c: In function ‘main’:
foo.c:10:26: warning: operation on ‘x’ may be undefined [-Wsequence-point]
10 | printf("%d ", SQUARE(++x)); // Expecting 16 but getting 25
| ^
foo.c:3:20: note: in definition of macro ‘SQUARE’
3 | #define SQUARE(x) (x)*(x)
| ^
The problem is, your macro expansion ends up doing ++x twice, so you're surprised by the result.
-
To be clear, (++x)*(++x) is undefined behavior because you cannot modify the same object more than once between sequence points. You can't and shouldn't expect any particular result from undefined behavior. It might even cause demons to fly out of your nose, which is usually not what one would expect.