Re: Signed and unsigned types issue
firstname.lastname@example.org (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();
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
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
adjustment is made.
> 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?
Keith Thompson (The_Other_Keith) email@example.com <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 06:00 AM.|
Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.