Search code examples
c++c-preprocessorincrementprefix

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;
}

Solution

  • 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.