Casting (signed long)(unsigned long)

Discussion in 'C Programming' started by curious_one, Jan 30, 2004.

  1. curious_one

    curious_one Guest

    All,
    I have a sample code that does something like this,

    unsigned long i = SOME_HUGE_VALUE;
    unsigned long j = SOME_HUGE_VALUE;

    void decrement_count()
    {
    if((signed long)j > 0)
    j--
    else
    printf("Empty");
    }

    void add_count()
    {
    if((signed long)j < i)
    {
    j++;
    }
    else
    {
    printf("Error");
    }
    }

    Will the casting in add_count truncate the j value while
    comparision,as a result j++ will have a value more than i at some
    point?

    regds
    curious
     
    curious_one, Jan 30, 2004
    #1
    1. Advertisements

  2. curious_one

    Dan Pop Guest

    Most likely, this code was written by someone who didn't know what he
    was doing. To behave correctly, both casts must be eliminated.

    Dan
     
    Dan Pop, Jan 30, 2004
    #2
    1. Advertisements

  3. curious_one

    Jack Klein Guest

    This may NEVER be true. An unsigned long with a value greater than
    ULONG_MAX will result in a negative value when cast to signed long on
    most implementations.
    No, there is no such guarantee.
     
    Jack Klein, Jan 31, 2004
    #3
  4. You mean: LONG_MAX
     
    Peter Nilsson, Jan 31, 2004
    #4
  5. curious_one

    curious_one Guest

    Dan,
    Thanks for your reply, I am not entirely clear on why the casts
    need to be eliminated. [Not that I know the reson why the casts are
    there in the first place :)], may i ask you the reason why the code
    will result in undefined behaviour ?

    thanks
    -curious
     
    curious_one, Feb 12, 2004
    #5
  6. curious_one

    pete Guest

    void decrement_count()
    {
    if (j != 0) j--;
    else printf("Empty");
    }

    void add_count()
    {
    if (j != 0lu - 1) {
    j++;
    } else {
    printf("Error");
    }
    }
    Conversion of out of range values to signed types,
    is implementation defined.
     
    pete, Feb 12, 2004
    #6
    1. Advertisements

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.