Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Meaning of ~0

74 views
Skip to first unread message

Old Wolf

unread,
Feb 1, 2014, 7:06:02 PM2/1/14
to
I'm sure this would have been asked before, but Google can't
cope with searching for tilde, so...

What does ~0 evaluate to?

N2521 just says "The operand of ~ shall have integral or
enumeration type; the result is the one's complement of
its operand." without any further explanation.

Does it mean the value whose representation is all-bits-1 ?
What if this is a trap representation?

Richard Damon

unread,
Feb 1, 2014, 8:19:06 PM2/1/14
to
The operation ~ is only defined for integral or unscoped enums (which
will also ultimately reduce to a integral type). For unsigned types, the
concept of a one's complement is well defined, being identical to the
value of MAX_INT - x (or what ever the max value of the type is), the C
standard actually gives this definition. For signed types, the bit by
bit definition still applies, but the "value" of the result will be
implementation defined (based mostly on the type of negative numbers the
machine uses) and may produce "trap" values.

In the case of all-bits-1 this is well defined for all 3 standard systems.

For two's complement it is -1
For one's complement it is -0
For Sign / Magnitude it is the most negative number of that type.

Paavo Helde

unread,
Feb 2, 2014, 3:02:37 PM2/2/14
to
Old Wolf <old...@inspire.net.nz> wrote in news:1022b30a-f150-48bf-99b8-
193197...@googlegroups.com:
0 is a signed int value. Bitwise operations depend on the representation
of signed types, which are implementation-specific, so not very reliable.
Also, if you assign the result to a value of potentially larger type
(e.g. unsigned long), it may fail to initialize higher bits. Using ~0U, ~
0UL, ~0ULL would be better.

Actually there is a standard idiom to obtain an unsigned value of any
type with all bits set, namely by converting -1 to this type, e.g.

unsigned long x = -1;

This is guaranteed to work as the C++ standard specifies such conversions
as modulo 2^n, meaning you get an unsigned value of 2^n-1, which means
all bits set. However, this it not very intuitive so may confuse novices.

hth


0 new messages