In the C language, what does "return ~0" mean?
I'm dealing with some C code that includes
return ~0;
What does that mean? It's pr开发者_开发百科etty much impossible to google for...
~ is a bitwise not/complement, aka it changes all 0's to 1's and vice-versa. ~0 is a value with all bits set to 1.
The key to answering this class of question as you inspect the code is to recognize enough of the structure of the language to know what question to ask. For example, the return
statement requires an expression, of a type compatible with the declared return type for the function itself.
Knowing that ~0
must be an expression, it is either a really funny way to write a number, or it is an operator you don't recognize applied to the constant zero. That latter hypothesis is easily checked, and googling for "C language operator" will quickly lead to dozens of tables of operators. Nearly any one of which will tell you that the ~
operator is a bitwise-not unary operator which inverts each individual bit of its operand. In this specific case, that converts the signed integer 0
to the integer represented with all its bits set.
On the majority of platforms you will encounter, that integer has the value -1.
The ~
(tilde) operator performs a bitwise complement on its single integer operand.
Complementing a number means to change all the 0
bits to 1
and all the 1
s to 0
s
Anyway, for search queries with special symbols like yours "return ~0;" you can use http://symbolhound.com/
It is pretty useful for programmer.
There are two independent parts here: return
and ~0
.
return
is a return statement. Read about it in your favorite C book.
~0
is an expression consisting of bitwise-complement operator ~
applied to integer constant 0
. All bits in a zero value of type int
are inverted (become 1) and the resultant int
value (with all bits set to 1) is what the ~0
expression evaluates to. On a two's complement machine a signed integral value with such bit pattern (111...1
) would represent -1
.
Not zero or True.
The tilde does a bitwise compliment of the number 0, which returns back a value with all bits set to 1, with whatever size of the return value (so you'd get 0xFF for a char, etc.)
精彩评论