if (~mask == 0){...}
I have encountered this thing in one of the .cpp files, and I wonder what is does ~ mean in c/c++?
if (~mask == 0){...}
I have encountered this thing in one of the .cpp files, and I wonder what is does ~ mean in c/c++?
It's a tilde and in C++ it means bitwise NOT.
For an eight-bit unsigned integer named mask
with the following bit representation:
0010 1100
the value of ~mask
is:
1101 0011
Notice how all the bits have been flipped.
For your if
condition (~mask == 0
) to evaluate to true:
~mask: 0000 0000
mask: 1111 1111
In such a case, mask
has the value 255
.
Apply the same logic to integers of different bit-widths and signedness, as appropriate.
(Note: In reality, if your system has 32-bit int
s, ~mask
will be 32-bit even if mask
was 8-bit. This is because ~
performs integral promotion. However, I ignore this fact for the above simple examples.)
Here's the formal definition:
[C++11: 5.3.1/10]:
The operand of˜
shall have integral or unscoped enumeration type; the result is the one’s complement of its operand. Integral promotions are performed. The type of the result is the type of the promoted operand. There is an ambiguity in the unary-expression˜X()
, whereX
is a class-name or decltype-specifier. The ambiguity is resolved in favor of treating˜
as a unary complement rather than treating˜X
as referring to a destructor.
As the passage reminds us, do not confuse bitwise NOT for the leading character in the name of a class destructor. It's interesting that ~
was chosen for destructors; arguably it's because one could perceive a destructor as the opposite (i.e. logical NOT) of a constructor.
it's a bitwise not. It inverts all of the bits of the variable. In this case your if will be true if all of the bits of "mask" are 1.
It is called the bitwise complement operator in C.
It inverts all bits of the (promoted) operand (a 0
becomes a 1
and a 1
becomes a 0
).
if (~mask == 0){...}
This checks if all bits of mask
are set to 1
.
its bitwise not....it gives the complement of the given number's binary representation! like if you write b=(~a); and a is equal to say 11 whose binary representation is 0000 1011...the it'll gives ...b=1111 0100 in binary