if (~mask == 0){...}
I have encountered this thing in one of the .cpp files, and I wonder what is does ~ mean in c/c++?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It’s a tilde and in C++ it means bitwise NOT.
For an eight-bit unsigned integer named
maskwith the following bit representation:the value of
~maskis:Notice how all the bits have been flipped.
For your
ifcondition (~mask == 0) to evaluate to true:In such a case,
maskhas the value255.Apply the same logic to integers of different bit-widths and signedness, as appropriate.
(Note: In reality, if your system has 32-bit
ints,~maskwill be 32-bit even ifmaskwas 8-bit. This is because~performs integral promotion. However, I ignore this fact for the above simple examples.)Here’s the formal definition:
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.