y"); else printf("x<=y"); } I was expecti...">

Why is unsigned int 1 lower than char y -1?

main() { unsigned x = 1; char y = -1; if (x > y) printf("x>y"); else printf("x<=y"); } 

I was expecting x>y , but I had to change the unsigned int to signed int to get the expected result.

+7
source share
2 answers

If char equivalent to signed char :

  • char raised to int (integer sentences, ISO C99 ยง6.3.1.1 ยถ2)
  • Since int and unsigned int have the same rank, int converted to unsigned int (Arithmetic Conversions, ISO C99 ยง6.3.1.8)

If char equivalent to unsigned char :

  • char can be converted to int or unsigned int :
    • If int can represent all unsigned char values โ€‹โ€‹(usually because sizeof(int) > sizeof(char) ), char converted to int .
    • Otherwise (usually because sizeof(char)==sizeof(int) ), char converted to unsigned .
  • Now we have one operand, int or unsigned int , and the other, unsigned int . The first operand is converted to unsigned int .

Integer promotions: an expression of type of a lower rank, which int converted to int if int can contain all the values โ€‹โ€‹of the original type, otherwise to unsigned int .

Arithmetic conversions. Try converting to a larger type. When there is a conflict between the signed and unsigned, if the larger (including the case when two types have the same rank) unsigned type, you should use unsigned. Otherwise, use a signature only if it can represent all values โ€‹โ€‹of both types.

Converts to integer types (ISO C99 ยง6.3.1.3):

The conversion of a value out of range to an unsigned integer type is performed using cyclic conversion (modular arithmetic).

Converting a value out of range to a signed integer type is determined by the implementation and may cause a signal (for example, SIGFPE).

+14
source

When using signed and unsigned in a single operation, the signed code received an automatic unsigned type conversion. If bit-bit -1 is considered an unsigned number, this is a very very high value. Therefore, x > y is false.

+3
source

All Articles