Reputation: 112
Could somebody explain why b = 150 ?
#define CUBE(X) ((X) * (X) * (X))
using namespace std;
int main( void )
{
int a = 3,b = 0;
cout << "before "<< endl;
cout << "a = " << a;
cout << endl;
cout << "b = " << b;
cout << endl;
cout << "after"<< endl;
b = CUBE( ++a );
cout << "a = " << a;
cout << endl;
cout << "b = " << b;
getchar();
return 0;
}
Upvotes: 1
Views: 664
Reputation: 385295
Because you're using a macro. Macros are not functions.
The line:
b = CUBE( ++a );
gets re-written as:
b = ((++a) * (++a) * (++a))
before your code compiles.
The code then invokes Undefined Behaviour because you increment a
several times between sequence points.
It would be better if you used a function instead.
Upvotes: 10
Reputation: 146988
Undefined behaviour- you modify a
more than once between sequence points. This is why inline
functions are the vastly superior option.
Upvotes: 3