Flora
Flora

Reputation: 309

Incrementing in C++ - Help understanding sample program output

I am currently learning C++ and I like to read and explore programs I find on the internet.

I have found this example C++ code, which gives "4 is greater than 2" as an output, but I cannot figure out why:

#include <stdio.h>
#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;
}

What I do not understand is: if you look at the segment which states

if( MAX( ++x, y ) == x )

it is supposed to increase the X variable by 1, then call MAX; at that point X should be 3. Instead, when you compile it the output is as aforementioned.

I have done some research on how the ++ operator works ( Incrementing in C++ ) but I could not get the solution anyway. Could you please explain me why this happens?

Thanks in advance for your help.

Upvotes: 0

Views: 93

Answers (1)

simonc
simonc

Reputation: 42165

The preprocessor expands your condition to

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

This increments x twice - ++x > y is equivalent to 3>2 so the condition evaluates true, resulting in ++x being evaluated again.

Also, as Benjamin Lindley points out, you need extra parentheses around the macro if you want it to return the maximum of two values in this case:

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

Upvotes: 4

Related Questions