Re: Signed and unsigned types issue

Discussion in 'C Programming' started by Phil Carmody, Sep 25, 2012.

  1. Phil Carmody

    Phil Carmody Guest

    (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);
    >
    > 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();


    If you want a long, why are you casting to int?

    value = -(long)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?


    Well, clearly the unary negation is applied to an unsigned type, that's
    correct. However, the unsigned int that you are left with after that
    negation is then converted to type long (retaining its value by zero
    extension) before the assignment takes place.

    Phil
    --
    Regarding TSA regulations:
    How are four small bottles of liquid different from one large bottle?
    Because four bottles can hold the components of a binary liquid explosive,
    whereas one big bottle can't. -- camperdave responding to MacAndrew on /.
     
    Phil Carmody, 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:
    598
    Jason Heyes
    Feb 14, 2005
  2. Sriniv

    Unsigned and signed char types

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

    , Feb 14, 2006, in forum: C Programming
    Replies:
    2
    Views:
    358
    Alex Fraser
    Feb 14, 2006
  4. pozz
    Replies:
    12
    Views:
    784
    Tim Rentsch
    Mar 20, 2011
  5. Keith Thompson

    Re: Signed and unsigned types issue

    Keith Thompson, Sep 25, 2012, in forum: C Programming
    Replies:
    0
    Views:
    302
    Keith Thompson
    Sep 25, 2012
Loading...

Share This Page