cmacrosswapconditional-operatorpreprocessor-directive

Getting unexpected results when using macros with arguments


#include <stdio.h>
#define big(a, b) a > b ? a : b
#define swap(a, b) temp = a; a = b; b = temp;

int main() {
    int a = 3, b = 5, temp = 0;
    if ((3 + big(a, b)) > b)
        swap(a, b);
    printf("%d %d", a, b);
}

Above code was given in a multiple choice question. I expected the answer to be 5 3. On running the code, output comes out to be 5 0. I've tried to make sense of this but my efforts have gone in vain. What's the working of this code?


Solution

  • Just expand the macros in the code and you will get

    int main() {
        int a = 3, b = 5, temp = 0;
        if ((3 + a > b ? a : b ) > b)
            temp = a;
        a = b;
        b = temp;    
        printf("%d %d", a, b);
    }
    

    As the first expression 3 + a in the conditional operator is equal to 6 then the result of the conditional operator is the value of a that is less than b.

    So the condition of the if statement evaluates to logical false and the statement

    temp = a;
    

    is skipped.

    As a result a will be equal to 5 and b will be equal to 0.

    You need to use parentheses. For example

    #define big(a, b) ( ( a ) > ( b ) ? ( a ) : ( b ) )
    #define swap(a, b) do { temp = ( a ); ( a ) = ( b ); ( b ) = temp; } while ( 0 )