jan.chludzinski@gmail.com wrote, On 07/05/08 19:44:
> Are the variables on the righthand side of an assignment statement
> treated strictly as values?
That is not the question you intended to ask. I think you wanted to know
if they are treated as values of the same type as the left hand side,
and the answer is no.
> That is, if in assigning to an "unsigned
> int" I shift a "unsigned char" 24 places to the left, can I trust that
> the compiler will use temp storage sufficient to hold the "unsigned
> int" and NOT result in an overflow (because I shifted an "unsigned
> char" 24 places)?
>
> Using gcc I tried the code below:
>
> #include <stdio.h>
>
> int main( int argc, char *argv[] )
> {
> unsigned char c[ 4 ] = { 0xff, 0xff, 0xff, 0xff };
> unsigned int ui;
>
> ui = (c[ 3 ] << 24) | (c[ 2 ] << 16) | (c[ 1 ] << 8) | c[ 0 ];
Each array element will be promoted to either int (if UCHAR_MAX <=
INT_MAX) or unsigned int (if INT_MAX < UCHAR_MAX <= UINT_MAX). Since the
latter is probably the case on your gcc implementation c[3]<<24 invoked
undefined behaviour.
> fprintf( stderr, "ui = %x\n", ui );
> }
>
> and got:
>
>> ui = ffffffff
>
> But validation through compilation is a dangerous thing!
Indeed, as the behaviour is undefined in this case it was "luck" you got
the answer you expected. You should cast to the correct unsigned type.
Also be aware that (unsigned) int could be only 16 bits.
--
Flash Gordon