Why does double negation force values to become a bool?
If x was a 4 bit word like 1010, and you did the operation !!x,
Rather it returns ...0001 or ...0000. Why is this?
In C, !x
is either 1 or 0, So !!x
is a "collapse to 0 or 1 operator" in the sense that any non-zero number is mapped to 1, and 0 stays as it is. This can be useful on occasions.
In C++, !x
is a bool
type, So !!x
is a "collapse to false or true operator" in the sense that any non-zero number is mapped to true
, and zero is mapped to false
.
The !
operator performs logical negation. If its argument is non-zero, it results in 0. If its argument is 0, it results in 1.
What you're describing is the bitwise complement operator , denoted by ~
.
These are both described in section 6.5.3.3 of the C standard:
4 The result of the ~
operator is the bitwise complement of its (promoted) operand (that is, each bit in the result is set if and only if the corresponding bit in the converted operand is not set). The integer promotions are performed on the operand, and the result has the promoted type. If the promoted type is an unsigned type, the expression ~E
is equivalent to the maximum value representable in that type minus E
.
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)
.
!
is a boolean operator, so it will convert the number into a bool (any non-zero value is true
, zero is always false
). That other !
inverts the bool.
上一篇: 实时检查恒定功能输入
下一篇: 为什么双重否定力值成为布尔?