gpt4 book ai didi

c++ - 针对 unsigned int 上的一元运算的编译器警告

转载 作者:可可西里 更新时间:2023-11-01 18:42:00 25 4
gpt4 key购买 nike

我有生成以下警告的示例代码(带有 SP1 的 VS2008 编译器):

warning C4146: unary minus operator applied to unsigned type, result still unsigned

代码:

void f(int n)
{
}

int main()
{
unsigned int n1 = 9;
f(-n1);
}

但是既然函数 f 将它的参数作为一个 int ,那么这段代码不应该在没有任何警告的情况下编译吗?

最佳答案

如果x类型为 unsigned int , 那么 -x 也是它实际上等同于 2<sup>n</sup>-x (其中 n 最有可能是 32)。为避免警告获得正确的行为,转换为int :

f(-static_cast<int>(n));

我建议阅读 C++ 标准的“表达式”一章。你会在表达式 -x 中看到积分促销发生在 x ,这意味着几乎任何东西都会被提升为 int ,但是 unsigned int不是。

看看这个非常有趣的例子:

template<class T>
void f(T x)
{
//somehow print type info about x, e.g. cout << typeid(x).name() or something
}

int main()
{
char x;
f(x);
f(+x);
f(-x);
}

打印:

char
int
int

但是char -> int是积分提升,而 unsigned int -> int是一个转换

关于c++ - 针对 unsigned int 上的一元运算的编译器警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4267194/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com