comparing unsigned and signed numbers

Discussion in 'Programmer's Corner' started by anhnha, Sep 13, 2014.

  1. anhnha

    Thread Starter Active Member

    Apr 19, 2012
    773
    45
  2. MrChips

    Moderator

    Oct 2, 2009
    12,418
    3,355
    Let us take a simple example. Suppose we have a 4-bit binary representation of both unsigned and signed numbers.
    Code (Text):
    1.  
    2.  
    3. Unsigned integers
    4. 0000 0
    5. 0001 1
    6. 0010 2
    7. 0011 3
    8. 0100 4
    9. 0101 5
    10. 0110 6
    11. 0111 7
    12. 1000 8
    13. 1001 9
    14. 1010 10
    15. 1011 11
    16. 1100 12
    17. 1101 13
    18. 1110 14
    19. 1111 15
    20.  
    21. Signed integers
    22. 1000 -8
    23. 1001 -7
    24. 1010 -6
    25. 1011 -5
    26. 1100 -4
    27. 1101 -3
    28. 1110 -2
    29. 1111 -1
    30. 0000 0
    31. 0001 1
    32. 0010 2
    33. 0011 3
    34. 0100 4
    35. 0101 5
    36. 0110 6
    37. 0111 7
    38.  
    You can see that if you were asking the question is 7 greater than -3
    you would get an incorrect answer if -3 was treated as an unsigned integer.
     
    anhnha likes this.
  3. anhnha

    Thread Starter Active Member

    Apr 19, 2012
    773
    45
    Thanks, that makes great sense!
    So without running the program, I guess the program will print out all array elements except the first one (assuming that signed number is treated as unsigned one by the compiler). Is this right?

    Code (Text):
    1.  
    2. #include"stdio.h"
    3. #include"stdlib.h"
    4. #define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))
    5. int array[] = {23,34,12,17,204,99,16};
    6. int main()
    7. {
    8. int d;
    9. for(d=-1;d <= (TOTAL_ELEMENTS-2);d++)
    10. printf("%d\n",array[d+1]);
    11. system("pause");
    12. return 0;
    13. }
    14.  
     
  4. anhnha

    Thread Starter Active Member

    Apr 19, 2012
    773
    45
    I think I realized my mistake above.
    In this case, possibly no elements will be printed at all.
    -1 here will be treated as 11111111 (unsigned int) = 255 that may be larger than TOTAL_ELEMENTS -2
     
Loading...