unsigned int and signed char comparison

后端 未结 4 801
死守一世寂寞
死守一世寂寞 2020-11-27 07:36

I am trying to compare an unsigned int with a signed char like this:

int main(){
  unsigned int x = 9;
  signed char y = -1;
  x < y ? printf(\"s\") : pri         


        
相关标签:
4条回答
  • 2020-11-27 08:07

    Ran the following code:

    int main(){
      unsigned int x = 9;
      signed char y = -1;
      printf("%u\n", (unsigned int)y);
      x < (unsigned int)y ? printf("s") : printf("g");
      return 0;
    }
    

    The output is:

    4294967295
    s
    

    After a casting, y takes a very large value. That is why output is s.

    0 讨论(0)
  • 2020-11-27 08:12

    Section 6.3.1.8, Usual arithmetic conversions, of C99 details implicit integer conversions.

    If both operands have the same type, then no further conversion is needed.

    That doesn't count since they're different types.

    Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.

    That doesn't count since one is signed, the other unsigned.

    Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.

    Bingo. x has a higher rank than y so y is promoted to unsigned int. That means that it morphs from -1 into UINT_MAX, substantially larger than 9.

    The rest of the rules don't apply since we have found our match but I'll include them for completeness:

    Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type.

    Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type.


    The ranks relevant to this question are shown below. All ranks are detailed in C99, section 6.3.1.1, Boolean, character, and integers so you can refer to that for further details.

    The rank of long long int shall be greater than the rank of long int, which shall be greater than the rank of int, which shall be greater than the rank of short int, which shall be greater than the rank of signed char.

    The rank of char shall equal the rank of signed char and unsigned char.

    0 讨论(0)
  • 2020-11-27 08:12

    The char is promoted to unsigned int, with a value of MAX_UINT, which is greater than 9.

    0 讨论(0)
  • 2020-11-27 08:14

    My guess is y is promoted to unsigned int which becomes a big value (due to wrapping). Hence the condition is satisfied.

    0 讨论(0)
提交回复
热议问题