unsigned int (c++) vs uint (c#)

前端 未结 3 808
难免孤独
难免孤独 2021-02-05 00:39

Following is the c# code:

   static void Main(string[] args)
    {
        uint y = 12;
        int x = -2;
        if (x > y)
            Console.WriteLine(\         


        
3条回答
  •  野的像风
    2021-02-05 01:31

    I don't know about the standard of C#, but in the C++ standard, usual arithmetic conversions would be applied to both operands of relational operators:

    [......enum, floating point type involed......] 
    
    — Otherwise, the integral promotions (4.5) shall be performed on both operands.
      Then the following rules shall be applied to the promoted operands:
    
        — If both operands have the same type, no further conversion is needed.
    
        — Otherwise, if both operands have signed integer types or both have
          unsigned integer types, the operand with the type of lesser integer
          conversion rank shall be converted to the type of the operand with
          greater rank.
    
        — Otherwise, if the operand that has unsigned integer type has rank
          greater than or equal to the rank of the type of the other operand, the
          operand with signed integer type shall be converted to  the type of the
          operand with unsigned integer type.
    
        — 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, the operand with unsigned integer type shall be converted
          to the type of the operand with signed integer type.
    
        — Otherwise, both operands shall be converted to the unsigned integer type 
          corresponding to the type of the operand with signed integer type.
    

    Thus, when unsigned int is compared with int, int would be converted to unsigned int, and -2 would become a very large number when converted to unsigned int.

提交回复
热议问题