comparing unsigned and signed numbers

MrChips

Joined Oct 2, 2009
30,813
Let us take a simple example. Suppose we have a 4-bit binary representation of both unsigned and signed numbers.
Code:
Unsigned integers
0000 0
0001 1
0010 2
0011 3
0100 4
0101 5
0110 6
0111 7
1000 8
1001 9
1010 10
1011 11
1100 12
1101 13
1110 14
1111 15

Signed integers
1000 -8
1001 -7
1010 -6
1011 -5
1100 -4
1101 -3
1110 -2
1111 -1
0000 0
0001 1
0010 2
0011 3
0100 4
0101 5
0110 6
0111 7
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.
 

Thread Starter

anhnha

Joined Apr 19, 2012
905
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:
#include"stdio.h"
#include"stdlib.h"
#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))
int array[] = {23,34,12,17,204,99,16};
int main()
{
int d;
for(d=-1;d <= (TOTAL_ELEMENTS-2);d++)
printf("%d\n",array[d+1]);
system("pause");
return 0;
}
 

Thread Starter

anhnha

Joined Apr 19, 2012
905
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
 
Top