3

I'm puzzled. Example:

int x=-1; 
unsigned y=0;
(x<y) ----> false

int8_t x=-1;
unint8_t y=0;
(x<y) ----> true

Additionally, the compiler raises warnings on the first comparison, but not the second. It seems that for

  • (int vs unsigned) - int promoted to unsigned
  • (intN_t vs uintN_t) - uintN_t promoted to intN_t

Why have this behaviour? Like... really?

gone
  • 2,587
  • 6
  • 25
  • 32

2 Answers2

3

Whenever you apply any binary arithmetic operator (including comparisons) to a pair of numeric types which are both shorter than int, C converts both operands to int before performing the operation.

Whenever you apply any binary arithmetic operator to a pair of numeric types which are the same size, mismatched in signedness, and not shorter than int, C converts the signed operand to unsigned before the operation.

These are two of the "integer promotion" rules. They are not terribly intuitive, and they are probably not what one would do if one were designing C from scratch today, but they are what they are and we are stuck with them.

zwol
  • 135,547
  • 38
  • 252
  • 361
2

This is a result of the usual integer conversions.

In the first case, both operands have rank at least that of int, and have the same rank, so they are converted to the unsigned integer type.

In the second case, int8_t is char (it has to be, if it exists at all), so both operands are promoted to int. Both -1 and 0 are representable in int, so there is no warning.

ecatmur
  • 152,476
  • 27
  • 293
  • 366
  • `short` can't be 8 bits, it is required to be able to represent at least the interval [-32767, 32767] (yes, not -32768, due to C99's bizarre belief that non-twos-complement arithmetic was still worth bothering to support). If `char` is *larger* than 8 bits, however, `int8_t` could be a special extended type. – zwol May 02 '13 at 16:58
  • http://stackoverflow.com/a/697531/195488 –  May 02 '13 at 17:02
  • If char is larger than 8 bits, you probably won't have int8_t (it's one of the types that's optional for an implementation to provide because the standard writers would like to think someone will implement C99 for a UNIVAC running somewhere). – Nicholas Wilson May 02 '13 at 17:31
  • @Zack oh, of course; forgot the minimum sizes. – ecatmur May 02 '13 at 17:52