James Kanze
11/28/2008 8:58:00 AM
On Nov 27, 11:34 pm, Juha Nieminen <nos...@thanks.invalid> wrote:
> Andrey Tarasevich wrote:
> > Probably not enough thinking? C-style cast to 'unsigned int'
> > is not a 'reinterpret_cast<unsigned int>' (ignoring for a
> > moment that there's no such thing as 'reinterpret_cast'
> > between integral types in C++). Conversion of a signed
> > value to 'unsigned int' evaluates to the original value
> > modulo 2^N, where N is the number of value bits in 'unsigned
> > int'. Which is exactly what you observe in your case.
> Another way of thinking about it:
> Since sizeof(int) and sizeof(unsigned int) is the same,
> then:
> int i = -1;
> unsigned ui = unsigned(i);
> int i2 = int(ui);
> After this i should be the same as i2 because only casts
> between integral types of the same size have been performed.
That's certainly not guaranteed, and typically will only be the
case on a 2's complement machine (and even then supposing that
the conversion to signed does no error checking). According to
the standard, the results of converting to a signed integral
type are implementation defined if the value being converted
cannot be represented in the target type. The C standard is
more explicit, and makes it clear that the implementation
defined "result" can include generating an implementation
defined signal.
> Sometimes casting can be a bit surprising. For instance:
> signed char c = -1;
> unsigned ui = unsigned(c);
> What is the value of ui?
UINT_MAX, of course. Conversion to unsigned integral types is
defined by the standard.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
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