On Oct 20, 7:51*pm, blargg....@gishpuppy.com (blargg) wrote:
> Does ~0 yield undefined behavior?
No.
> C++03 section 5 paragraph 5 seems to suggest so:
> > If during the evaluation of an expression, the result is not
> > mathematically defined or not in the range of representable
> > values for its type, the behavior is undefined [...]
> The description of unary ~ (C++03 section 5.3.1 paragraph
:
> > The operand of — shall have integral or enumeration type;
> > the result is the one's complement of its operand. Integral
> > promotions are performed. The type of the result is the type
> > of the promoted operand. [...]
> But perhaps "one's complement" means the value that type would
> have with all bits inverted, rather than the mathematical
> result of inverting all bits in the binary representation.
It's not really that clear what to expect on a machine not using
2's complement, but at the worst, it's unspecified or
implementation defined---not undefined behavior. (In general, I
would recommend avoiding ~, | and & on signed types.)
> For example, on a machine with 32-bit int, does one's
> complement of 0 (attempt to) have the value 2^31-1, which
> can't be represented in a signed int and is thus undefined, or
> does it have the value of whatever a signed int with all set
> bits would have (-1 on a two's complement machine)?
The wording is a bit sloppy, but what it doubtlessly means is
that you get a value with all bits set to one (in the specified
type). What that value is, of course, is probably
implementation dependent; it is -1 on a 2's complement machine,
but could very easily be 0 elsewhere.
> I used the ~0 case for simplicity; in practice, this issue
> might occur when ANDing with the complement of a mask, for
> example n&=~0x0F to clear the low 4 bits of n, or ~n&0x0F to
> find the inverted low 4 bits of n.
As long as the sign bit is 0, the behavior should be well
defined, with no ambiguities.
--
James Kanze (GABI Software) email:
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34