-2

The code below should return the value 216 but it returns 392 that is (7*7*8) . Can somebody please explain me how?

#include<iostream>
#define cube(x) (x*x*x)
    using namespace std;

    int main()
     {
        int x=5;
        cout<<cube(++x);
        cout<<endl;
        return 0;
      } 
xeon
  • 895
  • 9
  • 15

2 Answers2

2

You should really use a function and not a macro. The cube(++x) expands to

++x*++x*++x

which isn't at all what we want.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
  • thanks for ur suggestion . I'm not trying to solve a problem using this . I'm just curious about the behaviour . The thing is if x is replaced by x++ then shouldn't it be 7*8*9 ?? – xeon Nov 01 '15 at 08:43
  • It could be *any* result. You are not allowed to change the value of a variable more than once in an expression. If you do, like here, the language standard doesn't say what happens. So we don't know. – Bo Persson Nov 01 '15 at 08:54
2

After macro expansion you will get:

using namespace std;

int main()
 {
    int x=5;
    cout<<(++x*++x*++x);
    cout<<endl;
    return 0;
  }

and it is undefined behavior.

Just use a function instead of the cube macro:

int cube(int x) {
   return x * x * x;
}
Stas
  • 11,571
  • 9
  • 40
  • 58
  • thanks for ur suggestion . I'm not trying to solve a problem using this . I'm just curious about the behaviour . The thing is if x is replaced by x++ then shouldn't it be 7*8*9 ?? – xeon Nov 01 '15 at 08:42
  • 1
    @xeon That's the part where the undefined behaviour comes in. You can't expect any particular outcome from this program. – juanchopanza Nov 01 '15 at 08:43