Re: Signed and unsigned types issue

Discussion in 'C Programming' started by Keith Thompson, Sep 25, 2012.

  1. (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) <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"
    Keith Thompson, Sep 25, 2012
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Jason Heyes
    Replies:
    2
    Views:
    585
    Jason Heyes
    Feb 14, 2005
  2. Sriniv

    Unsigned and signed char types

    Sriniv, Jun 12, 2005, in forum: C Programming
    Replies:
    4
    Views:
    285
    William Ahern
    Jun 13, 2005
  3. signed and unsigned types

    , Feb 14, 2006, in forum: C Programming
    Replies:
    2
    Views:
    338
    Alex Fraser
    Feb 14, 2006
  4. pozz
    Replies:
    12
    Views:
    724
    Tim Rentsch
    Mar 20, 2011
  5. Phil Carmody

    Re: Signed and unsigned types issue

    Phil Carmody, Sep 25, 2012, in forum: C Programming
    Replies:
    0
    Views:
    310
    Phil Carmody
    Sep 25, 2012
Loading...

Share This Page