繁体   English   中英

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

[英]unsigned int (c++) vs uint (c#)

以下是c#代码:

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

这是c ++代码:

int _tmain(int argc, _TCHAR* argv[])
{
unsigned int y = 12;
int x = -2;
if(x>y)
    printf("x is greater");
else
    printf("y is greater");

return 0;
}

两者都给出了不同的结果。 我错过了什么基本的东西? 任何的想法?

C ++和C#是不同的语言。 在比较时,他们有不同的处理类型促销的规则。

在C ++和C中,它们通常被比较,就好像它们都是无符号的一样。 这称为“无符号保留”。 C ++和C编译器传统上使用“无符号保留”,并且在C ++标准和K&R中规定了它的使用。

在C#中,它们都被转换为有符号长整数然后进行比较。 这被称为“保值”。 C#指定保留值。

ANSI C还指定了值保留,但仅限于处理short和chars时。 短裤和字符(有符号和无符号)以保值的方式上转换为整数,然后进行比较。 因此,如果将未签名的short与已签名的short进行比较,结果就会像C#示例一样出现。 无论何时转换为更大的大小,都是以保值的方式完成的,但是如果这两个变量的大小相同(而不是短路或字符)并且其中一个是无符号的,那么它们将作为无符号数量进行比较。 ANSI C. 在comp.lang.c FAQ中对这两种方法的上下两侧进行了很好的讨论。

在C ++中,当比较unsigned intsigned intsigned int将转换为unsigned int 将负的signed int转换为unsigned int是通过添加大于12 UINT_MAX + 1来完成的,从而得到结果。

在C#中,如果得到相反的结果,则意味着在C#中,两个表达式都被转换为 signed int signed longlongSystem.Int641 ,然后进行比较。

在C ++中,您的编译器必须给出警告:

警告:有符号和无符号整数表达式之间的比较

规则:
始终认真对待编译器发出的警告!

1正如svick在评论中正确指出的那样。

我不知道C#的标准,但在C ++标准中, usual arithmetic conversions将应用于关系运算符的两个操作数:

 [......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. 

因此,当unsigned int与比较intint将被转换成unsigned int ,和-2当转换成将成为非常大数量的unsigned int

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM