Search code examples
cif-statementnegative-numbernegation

Does if (!(-1)) evaluate to true or false in C?


I know that 0 and NULL evaluate to FALSE on their own and I know that a negative integer or a positive integer evaluate to TRUE on their own.

My understanding is that the NOT operation will happen after evaluating the expression, so if (-1) will evaluate to TRUE, then applying the ! operand will mean NOT TRUE which equals FALSE. Is this the correct order of operations and is it correct that if (!(-1)) will evaluate to FALSE?


Solution

  • The evaluation of if (!(-1)) can be worked out by thinking about the operator precedences.

    Firstly the unary - is applied to 1 which produces an integral -1. Then this value is logically negated by the !. This involves collapsing -1 into a logical value. The rule for this in C is nice and simple for integral types: 0 is falsy and everything else is truthy.

    Therefore -1 is truthy and when the logical negation happens we get false.

    Therefore this statement is portably false.