8
main() {
    unsigned x = 1;
    char y = -1;

    if (x > y)
        printf("x>y");
    else
        printf("x<=y");
}

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

chqrlie
  • 131,814
  • 10
  • 121
  • 189
Furqan
  • 268
  • 1
  • 13

2 Answers2

15

If char is equivalent to signed char:

  • char is promoted to int (Integer Promotions, ISO C99 §6.3.1.1 ¶2)
  • Since int and unsigned int have the same rank, int is converted to unsigned int (Arithmetic Conversions, ISO C99 §6.3.1.8)

If char is equivalent to unsigned char:

  • char may be promoted to either int or unsigned int:
    • If int can represent all unsigned char values (typically because sizeof(int) > sizeof(char)), char is converted to int.
    • Otherwise (typically because sizeof(char)==sizeof(int)), char is converted to unsigned.
  • Now we have one operand that is either int or unsigned int, and another that is unsigned int. The first operand is converted to unsigned int.

Integer promotions: An expression of a type of lower rank that int is converted to int if int can hold all of the values of the original type, to unsigned int otherwise.

Arithmetic conversions: Try to convert to the larger type. When there is conflict between signed and unsigned, if the larger (including the case where the two types have the same rank) type is unsigned, go with unsigned. Otherwise, go with signed only in the case it can represent all the values of both types.

Conversions to integer types(ISO C99 §6.3.1.3):

Conversion of an out-of-range value to an unsigned integer type is done via wrap-around (modular arithmetic).

Conversion of an out-of-range value to a signed integer type is implementation defined, and can raise a signal (such as SIGFPE).

ninjalj
  • 42,493
  • 9
  • 106
  • 148
3

When using signed and unsigned in single operation the signed got promoted to unsigned by C's automatic type conversion. If the bit patter of -1 is considered an unsigned number then it is a very very high value. So x > y is false.

taskinoor
  • 45,586
  • 12
  • 116
  • 142
  • 1
    @taskinoor: It doesn't matter what the bit pattern of -1 is "considered as an unsigned number", it's the _value_ that matters when it is converted to an unsigned type. – CB Bailey Jul 02 '11 at 07:42
  • @Charles Bailey, that's what I meant. May be my language is not good enough. – taskinoor Jul 02 '11 at 07:44
  • 3
    @taskinoor: When you talk about the bit pattern of -1, it seemed to me that you were implying that the implicit promotion from `char` to `unsigned` depends on the underlying representation of a `char` in the implementation (e.g. two's complement) which is not correct. – CB Bailey Jul 02 '11 at 07:53
  • 1
    -1 bit pattern is irrelevant. Conversion to unsigned is an arithmetic operation not a bit-pattern-reinterpretation. – R.. GitHub STOP HELPING ICE Jul 02 '11 at 13:41