long conversion of short expression.

Karl Botts kdb at chinet.chi.il.us
Thu Aug 10 15:33:28 AEST 1989


>I agree that if the multiplication overflows, the result is undefined,
>but its type is still an int; if a later conversion to long is
>required, isn't the compiler required to perform the 'extl' anyway?
>That is, shouldn't the result of a conversion from int to long be in
>the numeric range of an int, even if the original int value was
>undefined?  Or is the compiler free to do whatever it likes with an
>entire expression if any sub-expression overflows?

It most certainly is not -- this would break reams of code, inclouding lots
of mine.  Casting an integral value to an integral value of a know size is
a time-honored and legitimate method of truncation.  For instance:

int i;
i = (char)i;

truncates the value in i to the width of a char.  Note that this is not
necessarily the same as either:

i &= 0xFF;

or

i &= 0x7F;

Also, on many architectures a compiler can figure out that it can do:

i = (char)i;

by fiddling with registers, like by clearing th uuper half of a chameleon-size
register or stuffing the wide value into a char-sized register.  Some might
be able to figure this out for:

i &= 0xFF;

but they couldn't for

i &= 0x7F;

This register operation is liable to be faster than fetching a constant and
doing the bitwise AND.  Hence the truncation cast is not only legal, but
useful -- you can't break it.



More information about the Comp.lang.c mailing list