An interesting post i found on linkedin
I am working on removing the compilation warnings of an old code, and I'm facing a lot of signed/unsigned comparation problems.
Then I had this doubt:
when you do:
signed int sigInt;
unsigned int uInt;
if ( sigInt > uInt ) ...
Will the expression be evaluated as both were unsigned, or is it platform specific?
I've made a simple test:
int x = -1;
unsigned int y = 10;
if ( x > y )
{
printf("xxx");
}
else
{
printf("yyy");
}
and it prints "xxx". But, when I've changed the "x" and "y" to:
signed char x = -1;
unsigned char y = 10;
it prints "yyy".
So I was wondering: how is the compiler supposed to work in this situation.
Then I had this doubt:
when you do:
signed int sigInt;
unsigned int uInt;
if ( sigInt > uInt ) ...
Will the expression be evaluated as both were unsigned, or is it platform specific?
I've made a simple test:
int x = -1;
unsigned int y = 10;
if ( x > y )
{
printf("xxx");
}
else
{
printf("yyy");
}
and it prints "xxx". But, when I've changed the "x" and "y" to:
signed char x = -1;
unsigned char y = 10;
it prints "yyy".
So I was wondering: how is the compiler supposed to work in this situation.
In the first case, the *standard conversion* from int to unsigned int is defined. In the second case, the signed char gets *promoted* to int. It is best to stay with a simple "int" (without signed or unsigned prefixed) and a simple "char" (without the prefixed "signed" or "unsigned") to side-step these kinds of problems.
Yes, in the second case, the *promotion* is defined as well, the unsigned the signed and unsigned chars get converted to int. So, in this case as well, *both* x and y get converted to int and only then the comparison is done - which correctly prints "yyy".
There was a typo in my last post - I see it only now: "the unsigned the signed and unsigned chars get ..." should read as "the signed and unsigned chars get converted ...".
This is all document in Stroustrup book - much of the stuff can be found in appendix but you'll also find bits and pieces in the main text.