0

I was trying to run a code.

#include<iostream>
#define CUBE(x)(x*x*x)
using namespace std;
int main(){
    int x=5;
    int y=CUBE(++x);
    cout<<y<<endl;
    return 0;
}

According to me its output should be 216 but surprisingly its output is coming out to be 392.Someone please help me to get logic behind this.

devnull
  • 118,548
  • 33
  • 236
  • 227
  • 1
    It's undefined behaviour. View the preprocessed output and you've got http://stackoverflow.com/questions/949433/could-anyone-explain-these-undefined-behaviors-i-i-i-i-i-etc – chris Apr 12 '14 at 05:36
  • `#define CUBE(x) ((x)*(x)*(x))` and `int y=CUBE(x+1);` is probably what you want. – devnull Apr 12 '14 at 05:38
  • 2
    Putting that define into a function will yield you the requested 216. – Vesper Apr 12 '14 at 05:38
  • 2
    might take the trophy for least helpful title in a SO post yet. – RobP Apr 12 '14 at 05:39
  • Your question is tagged C++, so please, for heaven's sake, unless this is an exercise, solve the problem with an inline function! – namezero Apr 12 '14 at 05:44

3 Answers3

2

Macros are just textual replacement. Think about what your macro invocation will produce:

int y = CUBE(++x);
// becomes
int y = (++x*++x*++x);

Modifying a variable more than once between sequence points is undefined behavior (look up "sequence points" for the details). Undefined behavior means that the behavior cannot be relied upon. This is one of the dangers of macros. If it was a function invocation it would work as expected since then ++x would only be evaluated once.

ooga
  • 15,423
  • 2
  • 20
  • 21
  • `++i, ++i;` or `++i || ++i` are not undefined behaviour so you should say, "Modifying a variable more than once in a sequence point is" (statement --> sequence point) – Grijesh Chauhan Apr 12 '14 at 05:44
  • @GrijeshChauhan Lazy wording. I've changed it. Thanks. – ooga Apr 12 '14 at 06:38
  • @Grijesh, those are the rules for C++98. In C++11 the rules for sequencing all changed and now it is horrifically complicated. For example, `i = ++i + 1;` is now well-defined (don't ask me to explain, but I read a SO thread about it). – M.M Apr 12 '14 at 07:02
  • @MattMcNabb Thanks MaTT! It has been more than 10 years I didn't use C++. I don't know C++98, 11. But I will read it... – Grijesh Chauhan Apr 12 '14 at 07:10
  • good luck :) I'm hoping someone will write a detailed, good article on the whole topic. – M.M Apr 12 '14 at 07:13
2

CUBE(++x) expands to ++x * ++x * ++x. Might be better to define this as an inlined function rather than a define. Something like:

inline int CUBE( int x )
{
    return x * x * x;
}

http://gcc.gnu.org/onlinedocs/gcc/Inline.html

Bradley Snyder
  • 228
  • 4
  • 7
1

you used macro so the call,

CUBE(++x)

is replaced by

++x*++x*++x so the output is not as you predicted.
When you use macro the call is replaced by the code defined in macro.

LearningC
  • 3,182
  • 1
  • 12
  • 19