无符号整型(C ++)与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; } 

两者都给出不同的结果。 我缺less一些基本的东西吗? 任何想法?

C ++和C#是不同的语言。 在进行比较时,他们有不同的处理types提升的规则。

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

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

ANSI C还规定了值的保留,但只有在处理短裤和字符的时候。 将短裤和字符(签名和未签名)上传到保值方式,然后进行比较。 所以如果将一个未签名的short与一个有符号的short进行比较,结果就会像C#的例子一样出现。 任何时候转换到一个更大的大小完成,它是在一个保值的方式完成,但如果两个variables是相同的大小(而不是短或字符)和任何一个是无符号的,那么他们被比较为无符号数量ANSI C. 在comp.lang.c FAQ中 ,对这两种方法的优缺点进行了很好的讨论。

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

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

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

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

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

1正如斯维克在评论中正确指出的那样。

我不了解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 intunsigned int进行比较时, int将被转换为unsigned int ,而当转换为unsigned int时, -2将变成非常大的数字。