Is !x equal to true when x is negative?

Viewed 322
int main() {
    
    int x = -1;
                    
    if (!x) {
        printf("Yes\n");
                
    }
}

Is !x true when x is a negative number or it's true when it's only 0?

4 Answers

For any non-zero x, !x will be zero. So, for x == -1, !x is false.

From cppreference:

The logical NOT operator has type int. Its value is ​0​ if expression evaluates to a value that compares unequal to zero. Its value is 1 if expression evaluates to a value that compares equal to zero.

Any non-zero value is true even if it is negative value(e.g. -1 is true). So, negation of true is false. In the case of x=-1, if (x) will be evaluated to true. Thus, if(!x) will be false, and the printf("Yes\n"); will never be executed.

Unless one is coding for an ancient dinosaur using non 2's complement with a negative zero, (-0 is negative and zero), for all integer negative numbers x: !x --> (int) 0.

The result of the logical negation operator ! is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has type int. The expression !E is equivalent to (0==E). C17dr § 6.5.3.3 5

Related