gpt4 book ai didi

c++ - 为什么按位否定运算符 "~"转换为 int? (从 ‘unsigned char’ 转换为 ‘int’ 可能会改变它的值)

转载 作者:行者123 更新时间:2023-11-28 02:21:33 25 4
gpt4 key购买 nike

GCC 4.9.1 报告“警告:从‘int’转换为‘unsigned char’可能会改变其值 [-Wconversion]”,代码如下

#include <cstdlib>

int main( int , char*[] ) {
unsigned char *dest = new unsigned char[16];
const unsigned char *src = new unsigned char[16];
for( size_t i = 0; i != 16; ++i) {
dest[i] = ~(src[i]);
}
return 0;
}

显然,srcdest都是指向 unsigned char 数组的指针我只希望后者成为前者的逐位否定。出于某种奇怪的原因 ~运算符(operator)似乎返回 int从而触发警告。为什么?这是有意为之的行为吗?

当然,我知道我可以使用 static_cast<unsigned char>()以防止警告,但我觉得其他地方不对劲,警告一开始就不应该出现。

最佳答案

我想字面上的答案是因为标准是这么说的。来自 [expr.unary.op]:

The operand of ~ shall have integral or unscoped enumeration type; the result is the one’s complement of its operand. Integral promotions are performed. The type of the result is the type of the promoted operand.

根据 [conv.prom] 是:

A prvalue of an integer type other than bool, char16_t, char32_t, or wchar_t whose integer conversion rank (4.13) is less than the rank of int can be converted to a prvalue of type int if int can represent all the values of the source type; otherwise, the source prvalue can be converted to a prvalue of type unsigned int.

并且 int 的等级高于 unsigned char。所以是的,这是预期的行为,显式 static_cast 会消除警告。

关于c++ - 为什么按位否定运算符 "~"转换为 int? (从 ‘unsigned char’ 转换为 ‘int’ 可能会改变它的值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32271852/

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