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

前端 未结 3 811
难免孤独
难免孤独 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:19

    In C++, when you compare an unsigned int and a signed int, the signed int is converted to unsigned int. Converting a negative signed int to an unsigned int is done by adding UINT_MAX + 1, which is larger than 12 and hence the result.

    In C#, if you are getting the opposite result then it means that in C# both the expressions are being converted to signed int signed long (long or System.Int64)1 and then compared.

    In C++, your compiler must have given you the warning:

    warning: comparison between signed and unsigned integer expressions

    Rule:
    Always take warnings emitted by the compiler seriously!

    1 As rightly pointed out by svick in comments.

提交回复
热议问题