Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C Programming (http://www.velocityreviews.com/forums/f42-c-programming.html)
-   -   Re: Signed and unsigned types issue (http://www.velocityreviews.com/forums/t952647-re-signed-and-unsigned-types-issue.html)

 Keith Thompson 09-25-2012 08:31 AM

Re: Signed and unsigned types issue

pozzugno@gmail.com (pozz) writes:
> I know it is dangerous to mix signed and unsigned types, and this
> situation is an example.
>
> With a compiler for a 16-bit embedded CPU, the following piece of code
> results in an error:
>
> unsigned int foo(void);
> long value;
> value = -foo();
> set_value(&value);

The expression `foo()` is of type unsigned int. The unary "-" is
applied to that unsigned value and yields an unsigned result.
Arithmetic on unsigned int wraps around modulo UINT_MAX+1; on a 16 bit
system, that's 65536. So -foo() has the value 65476, and is of type
unsigned int.

Assigning that value to a long object causes it to be converted to
(signed) long; since the value is representable in the target type, no

> If foo() returns 60, value will be 65476 and not -60. I solved adding a
> cast (considering that foo() returns small values, between 10 and 60, this
> should always work):
>
> value = -(int)foo();
>
> Anyway I want to understand what happens without the cast. Is the minus
> sign (sign inversion) applied to an unsigned type before assigning the
> result to the long (signed) type?

Yes.

--
Keith Thompson (The_Other_Keith) kst-u@mib.org <http://www.ghoti.net/~kst>
Will write code for food.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"

 All times are GMT. The time now is 05:24 AM.