为什么一个不喜欢的编译器铸造隐为uint的? [英] Why does a compiler dislike implicitly casting to uint's?
问题描述
我遇到了一对夫妇的关于C ++和C#UINT使用类似的怪癖,现在我想知道的理由(这可能是每一个例子完全不同)。对于这两个例子中,注意,我设置为最高警告级别进行编译。
I have run into a couple of similar quirks regarding uint usage in both C++ and C#, and now I'm wondering on the reasoning (which may be completely different for each example). For both of these examples, note that I am compiling with the warning levels set to maximum.
(1)GCC抱怨在以下一个int比较为uint,而VC ++不会:
(1) gcc complains about comparing an int to a uint in the following, whereas vc++ does not:
uint foo = <somevalue>;
if( foo == ~0 ) //right here
...
相较于0是不会对GCC和VC ++的铸造就好了。
Comparing to 0 is just fine without any casting on both gcc and vc++.
(2)在C#3.5中,我只是碰到了一个类似的问题。以下工作正常:
(2) In C# 3.5, I just ran into a similiar issue. The following works fine:
uint foo = 1;
uint bar = 2;
但是,这给出了一个UINT / INT警告:
But this gives a uint/int warning:
bool condition = <somevalue>;
uint foo = condition ? 1 : 2; //right here
是什么给了,为什么编译器有立即值签订岬如此敏感?从变量分配的时候,但是这只是没有任何意义,我立即值我完全理解的问题;有没有在防止被允许这种行为解析一些隐藏的困难吗? ?还是什么
What gives, why is the compiler so sensitive about signed-ness of immediate values? I completely understand the issue when assigning from variables, but this just doesn't make sense to me for immediate values; is there some hidden difficulty in the parsing that prevents this behavior from being allowed? Or what?
修改是的,我知道我可以后缀我的号码与U,但回避我的问题,这是关于的隐的铸造左手侧,没有明确铸造右手边。
Yes, I know I can suffix my numbers with 'u', but that sidesteps my question, which is about implicitly casting to the left-hand-side, not explicitly casting the right-hand-side.
推荐答案
我不能说为 GCC
,但作为C#3编译器,你需要明确地告诉它,这些整数
应当是无符号:
I can't speak for gcc
but as for the C# 3 compiler you need to explicitly tell it that these ints
ought to be unsigned:
uint foo = condition ? 1U : 2U;
C#编译器的喜欢 整数
,并假定范围内的整数
所有整数值。由于您的表达式使用条件运算符的编译器是太急于假设你的文字值是整数
,然后分配失败。
The C# compiler loves ints
and assumes all integral values within range are ints
. Since your expression is using a conditional operator the compiler is too eager to assume your literal values are ints
and then the assignment fails.
修改注意,我说的积分值的是范围内的的 System.Int32
。考虑这个例子:
Note that I said integral values that are within range of a System.Int32
. Consider this example:
using System;
class Program
{
static void Main()
{
Console.WriteLine(1.GetType());
Console.WriteLine(2147483648.GetType());
}
}
输出:
System.Int32
System.UInt32
这篇关于为什么一个不喜欢的编译器铸造隐为uint的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!