What's the difference between (size_t)-1 and ~0?
What's the difference between (size_t)-1 and ~0?
Type and value differ.
(size_t)-1
is the same value as SIZE_MAX
and has a type of size_t
.
~0
is often -1 and has the type of int
.
Assigning both of those to a size_t
will result in SIZE_MAX
.
size_t a = (size_t)-1;
size_t b = ~0;
In the 2nd case, -1
is assigned to a b
and undergoes a conversion first, wrapping around the -1 to the maximum size_t
value.
(size_t)-1
is of type size_t
. It typically has a value of 232-1 or 264-1 (4294967295
or 18446744073709551615
).
~0
is of type int
, and has the value -1
on a 2's-complement system (i.e., just about everywhere).
Both are likely to have the same bit pattern -- if int
and size_t
are the same size, which they very commonly are not.
If you want the maximum value of type size_t
, you can use the SIZE_MAX
macro, defined in <stdint.h>
. If you're using an older implementation (pre-C99) that doesn't provide SIZE_MAX
, (size_t)-1
will work. I'm not sure why you'd want to write ~0
rather than -1
-- unless perhaps you're considering non-two's-complement systems.
Note that the previous answers assume a 2's complement machine (very likely to be the case these days, but not guaranteed).
If you had a sign-magnitude machine then -1
would have a sign bit and least significant bit set with all others clear, if you had a 1's complement machine then -1
would have all bits but the LSB set.
In all of these cases (including the common 2's complement machine), ~0
has all bits set.