tech-net archive

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]

Re: foo = (unsigned)bar; (was Re: dhcpcd-4.0.0-alpha1 ready for review)

> OK, this piqued my curiosity last night. What would this be expected to do

> signed char bar;
> unsigned char foo;
> foo = (unsigned)bar;

What you expect it to do depends on how well you know C.  What it does,
conceptually, is

- Sign-extend bar to int.
- Convert that int to unsigned int.
- Truncate that unsigned int to unsigned char
- Store the resulting unsigned char in foo.

On most machines, the "as if" rule lets the compiler convert this into
"move one byte from bar to foo".  (Maybe that's true on all machines,
provided you read "byte" as "char-sized unit of memory"; I'd have to
think about it hard to be sure; I suspect non-2's-complement-binary
machines may do something funkier.)

> IMO, only two things are possible here
> 1) type is preserved, so bar is correctly cast to an unsigned char
> 2) type is silently changed, so bar is incorrectly cast to an
>    unsigned (and I guess) int


What's incorrect about bar being cast to an unsigned int?  That's
exactly what happens (passing through signed int in the process, as
signed char rvalues always do).

/~\ The ASCII                           der Mouse
\ / Ribbon Campaign
 X  Against HTML     
/ \ Email!           7D C8 61 52 5D E7 2D 39  4E F1 31 3E E8 B3 27 4B

Home | Main Index | Thread Index | Old Index