Search code examples
c++postfix-operatorprefix-operator

Prefix increments variable twice in C++


I'm facing a somewhat classic exam question around postfix and prefix operators, prefix that I can't wrap my head around. Consider the following:

#define MAX( a, b ) ( a > b ) ? (a) : (b) 

int main()
{
    int x = 2, y = 2;

    if( MAX( ++x, y ) == x )
    {
        printf( " %d is greater than %d ", x, y );
    }

    return 0;
}

The exam question asks for the output of the program. To me it would be "3 is greater than 2" but the actual output is "4 is greater than 2"

I understand how post and prefix work (or at least I thought so) but I don't get how the variable gets incremented twice. Any explanation on this?


Solution

  • The makro is expanded to

    ( ++x > y ) ? (++x) : (y)
    

    There is your double increment.