对 unsigned int 进行一元运算的编译器警告
我有这个示例代码,它生成以下警告(带 SP1 的 VS2008 编译器):
警告 C4146:一元减运算符 应用于无符号类型,结果仍然 未签名
Code:
void f(int n)
{
}
int main()
{
unsigned int n1 = 9;
f(-n1);
}
但是由于函数 f
将其参数作为 int
,因此这段代码不应该在没有任何警告的情况下进行编译吗?
I have this sample code which generates the following warning (VS2008 compiler with SP1):
warning C4146: unary minus operator
applied to unsigned type, result still
unsigned
Code:
void f(int n)
{
}
int main()
{
unsigned int n1 = 9;
f(-n1);
}
But since function f
is taking it's parameter as an int
shouldn't this code compile without any warnings?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果
x
是unsigned int
类型,那么-x
也是这样,它实际上相当于2n-x
(其中n
最有可能是 32)。为了避免警告并获得正确的行为,请强制转换为 int:我建议阅读 C++ 标准的“表达式”一章。您将看到,在表达式
-x
中,整型提升发生在x
上,这意味着几乎所有内容都会提升为int
,但是unsigned int
不是。看看这个非常有趣的例子:
prints:
But
char
->int
是整数提升,而unsigned int
->int
是一个转换if
x
is of typeunsigned int
, then so is-x
and it is virtually equivalent to2n-x
(wheren
is most likely 32). To avoid the warning and get correct behavior, cast toint
:I would recommend reading the "Expressions" chapter of the C++ standard. There you'll see that in the expression
-x
integral promotions take place onx
, which means that almost anything gets promoted toint
, butunsigned int
is not.Look at this very interesting example:
prints:
But
char
->int
is an integral promotion, whereasunsigned int
->int
is a conversion标准5.3.1/7
还有关于积分促销4.5/1的段落
即 unsigned int 不会被提升为 int。
Standard 5.3.1/7
And the paragraph on Integral Promotion 4.5/1
i.e. an unsigned int will not be promoted to an int.
参数是按值传递的。在函数调用 f(-n1) 中,在将参数传递给函数之前应用运算符。因此发出警告。
The parameter is pass by value. In the function call, f(-n1), the operator is applied before passing the parameter to the function. Hence the warning.
编译器警告您,将一元减号应用于无符号 int 是一件不寻常的事情,并且可能不会给出您期望的结果。如果您使用的是 32 位编译器,则在这种情况下获得的结果将相当于调用 f(4294967287u)。
The compiler is warning you that applying unary minus to an unsigned int is an unusual thing to do and may not give the result you expect. The result you get in this case will be equivalent to calling f(4294967287u) if you are using a 32-bit compiler.