jan.chludzinski@[EMAIL PROTECTED]
wrote:
> Are the variables on the righthand side of an assignment statement
> treated strictly as values?
No, but mostly yes. In right-hand sides like `&x' or
`sizeof x', the variable `x' is used only for its location
or for its type, not for its value. But in "arithmetic"
right-hand sides like `x + 3' or `x << 2' or just `x', the
variable's value is used.
> That is, if in assigning to an "unsigned
> int" I ****ft 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 ****fted an "unsigned
> char" 24 places)?
No. The assignment target -- the left-hand side -- does
not influence how the right-hand side is evaluated. On most
systems[*] your `unsigned char' value will be promoted to a
plain (signed) `int', which will then be ****fted left 24 places.
There'll be trouble if `int' has 24 or fewer bits (16, for
example), or if the ****ft tries to slide a non-zero bit from
a value position into the sign position.
What you need is
unsigned char uc = ...;
unsigned int ui = (unsigned int)uc << 24;
.... and this still contains the assumption that `int' is at
least 25 bits wide.
[*] Exception: On "exotic" systems like some digital signal
processors, characters and ints have the same width and an
`unsigned char' promotes to an `unsigned int' instead.
> 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 ];
> fprintf( stderr, "ui = %x\n", ui );
> }
>
> and got:
>
>> ui = ffffffff
You were lucky. Or maybe unlucky.
> But validation through compilation is a dangerous thing!
I'd have said "unreliable" rather than "dangerous," but
the sentiment is right.
--
Eric.Sosman@[EMAIL PROTECTED]


|