Reason for following C function, why it goes to else part

Discussion in 'General Electronics Chat' started by aamirali, Nov 6, 2012.

  1. aamirali

    Thread Starter Member

    Feb 2, 2012
    415
    1
    Signed integers shall not be combined with unsigned integers in comparisons or expressions. Insupport of this, decimal constants meant to be
    unsigned should be declared with a ‘u’ at the end.

    Example:
    uint8_t a = 6u;
    int8_t b = -9;
    if (a + b < 4)
    {
    // This correct path should be executed
    // if -9 + 6 were -3 < 4, as anticipated.
    }
    else
    {
    // This incorrect path is actually executed,
    // as -9 + 6 becomes (0xFF – 9) + 6 = 252.
    }
     
  2. takao21203

    Distinguished Member

    Apr 28, 2012
    3,577
    463
    1. have you tried ((a+b)<4)
    2. have you tried a+(int8_t)b
     
  3. aamirali

    Thread Starter Member

    Feb 2, 2012
    415
    1
    Checked but it goes to else part
     
  4. takao21203

    Distinguished Member

    Apr 28, 2012
    3,577
    463
    then try to cast a.
     
  5. spinnaker

    AAC Fanatic!

    Oct 29, 2009
    4,866
    988

    What have you done to debug your code?
     
  6. MrChips

    Moderator

    Oct 2, 2009
    12,420
    3,355
    Two mistakes:

    1) As takao already pointed out, the if statement is incorrectly stated.
    it should be if ( (a+b) < 4 )

    2) Why are you mixing signed with unsigned?
    The problem may reside in the compiler, not in the MCU execution.

    If b is -9, then it is still 256 - 9 = 247 (in binary) as stored in the MCU.

    Hence -9 + 6 = 253 in both cases.

    It depends on how the compiler typecasts (a + b) < 4. Don't try to confuse the compiler. You should typecast to the same type yourself.

    There are 10 types of people in the world, those who understand binary and those who don't.
     
  7. ChandlerW

    Member

    Feb 15, 2011
    44
    0
    Try using the debugger to view the variables. Step through them one at a time.
    If that doesn't work for you, put cout << in several places to evaluate your variables as the program executes.
     
    Last edited: Nov 6, 2012
Loading...