Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C Programming > Re: Signed and unsigned types issue

Reply
Thread Tools

Re: Signed and unsigned types issue

 
 
Keith Thompson
Guest
Posts: n/a
 
      09-25-2012
http://www.velocityreviews.com/forums/(E-Mail Removed) (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
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?


Yes.

--
Keith Thompson (The_Other_Keith) (E-Mail Removed) <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"
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: Signed and unsigned types issue Phil Carmody C Programming 0 09-25-2012 08:52 AM
(int) -> (unsigned) -> (int) or (unsigned) -> (int) -> (unsigned):I'll loose something? pozz C Programming 12 03-20-2011 11:32 PM
signed and unsigned types Bilgehan.Balban@gmail.com C Programming 2 02-14-2006 08:30 PM
Unsigned and signed char types Sriniv C Programming 4 06-13-2005 03:31 AM
Casting between signed/unsigned pointer types. Jason Heyes C++ 2 02-14-2005 08:03 AM



Advertisments