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?
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?
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.
Per the C standard (draft C11, exactly) 6.5.3.3 Unary arithmetic operators, paragraph 5 (bolding mine):
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).
So the ! applied to a negative number is true.
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 to0, 1 if the value of its operand compares equal to 0. The result has typeint. The expression!Eis equivalent to(0==E). C17dr § 6.5.3.3 5