Search code examples
cmacrosternary

Ternary Operators and Macros #define


I am confused on the ternary operator outputs if it is used in a macro. Why is the output 3 and 0?

#define test(x,y)(! y ? 0 : x/y)

int main(void){
printf("%d",test(2+2,2));
printf("%d",test(4,-1-1));
return(0);
}

Solution

  • When you are confused about the usage of a macro, copy-paste it where it is being used and evaluate from there:

    int main(void){
        printf("%d", ! 2 ? 0 : 2+2 / 2);
        printf("%d", ! -1 - 1 ? 0 : 4 / -1 - 1);
        return(0);
    }
    

    The second argument to the first printf call goes: if ! 2 is true, return 0, otherwise return the expression (2+2) / 2. Since ! 2 is false, the expression 2+2 / 2 is returned, and its result is clearly 3.


    The second argument to the second printf call goes: if ! -1 - 1 is true, return 0, otherwise return the expression 4 / -1 - 1.

    The expression ! -1 -1 is actually interpreted as !(-1) - 1, since the ! (logical NOT) operator has precedence over the - (subtraction) operator.

    !(-1) becomes 0 (-1 is a truthy value, which, when negated, becomes a falsy one, i.e. 0).

    Then, 0 - 1 becomes -1, which is a truthy value, therefore the truthy value of the ternary operator is returned, i.e. 0.