wolf3d
wolf3d

Reputation: 112

Prefix increment in C++ preprocessor

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

Answers (3)

Lightness Races in Orbit
Lightness Races in Orbit

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

Puppy
Puppy

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

Benoit
Benoit

Reputation: 79215

(++a) * (++a) * (++a) is undefined behaviour.

Upvotes: 3

Related Questions