-2

I got this code compiled in VC++ and GCC that produces different outputs and appreciate if someone can point me out where the things get wrong.

#include "stdio.h"

#define Cube(x) x*x*x

int main(void){

    int x=5;
    printf("%d\r\n", Cube(x++));

return 0;
}

In GCC, the displayed value is 210 (=5*6*7) and in VC++2010 its 125 (=5*5*5).

If I do this,

#include "stdio.h"

#define Cube(x) x*x*x

int main(void){

    int x=5;
    printf("%d\r\n", Cube(++x));

return 0;
}

VC++ prints 512 (=8*8*8) and GCC prints 392 (=7*7*8).

Appreciate if someone can say whats going on.

SamR
  • 384
  • 3
  • 12
  • 1
    Incorrect code *should* produce different results on different compilers. And it should also produce warnings if they're turned on. So turn on warnings, and change the code to something correct. – Lee Daniel Crocker Apr 21 '15 at 22:31
  • this is a case where (besides the undefined behaviour from the 'side effect'') it would be necessary to write the 'x*x*x' as '(x)*(x)*(x)' to avoid certain 'text replacement' problems. In general, do not incorporate 'side effects' into the parameters for a macro. – user3629249 Apr 21 '15 at 22:32
  • Thanks for your responses. I do understand now. – SamR Apr 22 '15 at 12:50

1 Answers1

3

The line

printf("%d\r\n", Cube(x++));

is pre-processed to:

printf("%d\r\n", x++*x++*x++));

That is cause for undefined behavior.

printf("%d\r\n", ++x*++x*++x));

is also cause for undefined behavior.

See
Why the output of this program is 41? is it undefined behavior?
Why are these constructs (using ++) undefined behavior?

You can avoid the problem by converting Cube to a function. The program below is well behaved.

#include "stdio.h"

int Cube(int x)
{
   return x*x*x;
}

int main(void)
{
   int x=5;
   printf("%d\r\n", Cube(x++));
   printf("%d\r\n", Cube(++x));

   return 0;
}
Community
  • 1
  • 1
R Sahu
  • 204,454
  • 14
  • 159
  • 270