Hi
I'm dealing with some C code that includes
return ~0;
What does that mean? It's pretty much impossible to google for...
Hi
I'm dealing with some C code that includes
return ~0;
What does that mean? It's pretty much impossible to google for...
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
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.)
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
.
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.