Casting Signed to Unsigned: Undefined Behavior?
Hi,
First take a look at this quote from the C++03 standard:
Quote:
Originally Posted by 4.7 Integral conversions
If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source
integer (modulo 2n
where n is the number of bits used to represent the unsigned type). [Note: In a two’s
complement representation, this conversion is conceptual and there is no change in the bit pattern (if there
is no truncation). ]
This is the closest thing I can find in the standard that explains this behavior:
unsigned int Foo = (int)-4;
I would think this is implementation-specific behavior (Or undefined behavior). I have two questions:
1) What is the dummy's translation of the quoted standard rule above?
2) What does the standard say about the code snippet above (Assigning signed to unsigned)?
Thanks.
Re: Casting Signed to Unsigned: Undefined Behavior?
Quote:
Originally Posted by MrDoomMaster
1) What is the dummy's translation of the quoted standard rule above?
The relevant portion is when they say that the cast simply re-interprets the bit pattern.
Most computers are twos-complement these days, which essentially means they used the most significant bit as a sign bit. Thus all negative values become extremely large positive values, and the rest stay the same. In particular -1, which usually has bit a pattern of 32 1's, becomes the maximum unsigned int value.
Re: Casting Signed to Unsigned: Undefined Behavior?
Actually it is the other way around....
Regardless of the actual implementation of integers, the result is perfectly defined as stated in the standard.
It so happens that this is identical to "just reintrepreting the bit patten" when the representation is twos-complement (as stated, the most common).
This was done for efficiencies sake since the overhead is 0 on a 2s complement based machine, but all other internal representations MUST provide the identical translation in value.
So if you have a machine which uses bi-quinary for the internal representation (quick name the machine :D ), then you have ALOT of work to do....