What does !<number>
in c means. For example !-2
or !3
?
cout << !-2;
Output:
0
cout << !3;
Output:
0
What does !<number>
in c means. For example !-2
or !3
?
cout << !-2;
Output:
0
cout << !3;
Output:
0
!
is the logical negation operator. From the C Standard (6.5.3.3 Unary arithmetic operators)
5 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).
And from the C++ Standard (8.3.1 Unary operator)
9 The operand of the logical negation operator ! is contextually converted to bool (Clause 7); its value is true if the converted operand is false and false otherwise. The type of the result is bool.
So, for example, this expression
cout << !-2;
according to the C quote is equivalent to
cout << ( 0 == -2 );
In C the result of the operator has the type int
while in C++ the result of the operator has the type bool
.
Pay attention to that in C++ you may use the alternative token not
. For example the above statement can be rewritten like
cout << not -2;
In C you can include the header <iso646.h>
and use the macro not
as an alternative record for the operator !
.
And one more trick. If for example you want from a C function to return an integer expression preliminary converting it either exactly to 1 or to 0 you can write for example
return !!expression;
That is if expression
is not equal to 0
then the first applying of the operator !
converts the expression to 0
and the second applying the operator !
converts the result expression to 1
.
It is the same as if to write
return expression == 0 ? 0 : 1;
but more compact.
It's called a "logical not". The expression evaluates to false if the operand is nonzero and true if the operand is zero. Applying logical not to negative zero also returns true.
Unary operator !
is the logical negiation (i.e. NOT) operator. When the operand is true, the result is false and when the operand is false, the result is true. Integers operand is implicitly converted to bool value. Zero is false and all other numbers are true.