-1

see code below . The output is 49 ( 7*7 = 49) . How this could happen? can somebody explain in details.

#include <stdio.h>
#define SQUARE(X) X * X
#define PR(X) printf("The result is %d.\n", X)

int main(void) {
  int x = 5;
  printf("x = %d\n", x);
  PR(SQUARE(++x)); // print out 49 but x is 5

  return 0;
}
  • This is the very classic example of a macro pitfall. https://gcc.gnu.org/onlinedocs/cpp/Macro-Pitfalls.html – Eugene Sh. Aug 30 '22 at 21:03
  • 1
    just.... use a function, please – user438383 Aug 30 '22 at 21:03
  • The macro also needs parentheses: `#define SQUARE(X) ((X) * (X))`. Consider that will happen with `SQUARE(2+1)` which yours expands to `2 + 1 * 2 + 1` which is `5` not `9`. – Weather Vane Aug 30 '22 at 21:35
  • @WeatherVane trying it with your suggestion does not make any difference in relation to the question . – Alan M Aug 31 '22 at 06:50
  • @AlamM that is because in this case `7 * 7` evaluates the same as `((7) * (7))`. The comment wasn't a suggestion, but is pointing out a **fault** in the macro. – Weather Vane Aug 31 '22 at 08:24

1 Answers1

3

It will expand this way:

PR(SQUARE(++x));
==>
PR(++x * ++x)
==>
printf("The result is %d.\n", ++x * ++x);

And, modifying variable x twice without a "sequence-point" (mainly, a semi-colon ;, but there are other sequence-points) creates Undefined Behavior

abelenky
  • 63,815
  • 23
  • 109
  • 159
  • Thanks . Undefined Behavior should yield different result once executed many times; However, seems it is up to GCC interpretation to increment x twice and multiply it with each other like 7*7. My compiler . GCC (MinGW.org GCC-6.3.0-1) 6.3.0. Thanks for your support – amed svensson Aug 31 '22 at 20:39
  • No, Undefined Behavior does ***not*** mean *"random, unpredictable, unstable behavior"*. It may very well be consistent within one compiler. But another compiler or platform or build may produce a wildly different, behavior while still being a completely Standard Compiler because the code you gave does not have a Defined Behavior. – abelenky Aug 31 '22 at 20:49
  • Many thanks for clarification. I have noted this – amed svensson Sep 02 '22 at 07:30