看看这个C代码:
int main()
{
unsigned int y = 10;
int x = -2;
if (x > y)
printf("x is greater");
else
printf("y is greater");
return 0;
}
/*Output: x is greater.*/
Run Code Online (Sandbox Code Playgroud)
我理解为什么输出是x更大,因为当计算机比较它们时,x被提升为无符号整数类型.当x被提升为无符号整数时,-2变为65534,绝对大于10.
但是为什么在C#中,等效代码会产生相反的结果呢?
public static void Main(String[] args)
{
uint y = 10;
int x = -2;
if (x > y)
{
Console.WriteLine("x is greater");
}
else
{
Console.WriteLine("y is greater");
}
}
//Output: y is greater.
Run Code Online (Sandbox Code Playgroud)
Ree*_*sey 20
在C#中,双方uint
并int
得到提升到一个long
比较之前.
这4.1.5 Integral types
在C#语言规范中有记录:
对于二进制+, - ,*,/,%,&,^,|,==,!=,>,<,> =和<=运算符,操作数转换为类型T,其中T是第一个int,uint,long和ulong,可以完全表示两个操作数的所有可能值.然后使用类型T的精度执行操作,结果的类型是T(或关系运算符的bool).不允许一个操作数为long类型,另一个操作数为binary类型的二元运算符.
由于long
第一种类型可以完全代表所有int
和uint
值,因此变量都被转换为long
,然后进行比较.
小智 9
在C#中,在int和uint的比较中,两个值都被提升为long值.
"否则,如果任一操作数的类型为uint而另一个操作数的类型为sbyte,short或int,则两个操作数都将转换为long类型."
http://msdn.microsoft.com/en-us/library/aa691330(v=vs.71).aspx
归档时间: |
|
查看次数: |
1278 次 |
最近记录: |