c++ - -Wconversion warning while using operator <<= on unsigned char

标签 c++ gcc bitwise-operators unsigned-char

当我用 gcc 编译以下代码时:

int main()
{
  unsigned char c = 1;
  c <<= 1;  // WARNING ON THIS LINE
  return 0;
}

我收到这个警告:

conversion to ‘unsigned char’ from ‘int’ may alter its value [-Wconversion]

为什么?这段代码有什么问题?其实,我真的可以使用oprator <<=吗?在 unsigned char 上变量 ?

编译命令:

g++ test.cpp -Wconversion -o test.exe

最佳答案

这是一个有效的警告:

c <<= 1;

相当于:

c = c << 1

<<的规则假设操作数被提升,在这种情况下将提升为 int结果是提升的类型。所以会有一个从int的转换至 unsigned char最后可能会导致值发生变化。

代码有效,警告告诉您正在进行隐式转换,在某些情况下转换可能会改变值。使用强制转换将使警告静音。隐式转换的结果可能非常违反直觉,并且在某些情况下是未定义的行为。查看gcc Wconversion wiki for some details .

如果不手动扩展操作并使用 static_cast,我看不到消除警告的方法:

c = static_cast<unsigned char>( c << 1 );

正如我们可以从这个 gcc bug report 的长线程中看到的那样并非所有人都认为这是此警告的有用案例。

引用自draft C++ standard5.8移位运算符:

The operands shall be of integral or unscoped enumeration type and integral promotions are performed. The type of the result is that of the promoted left operand [...]

来自5.17部分赋值和复合赋值运算符:

The behavior of an expression of the form E1 op = E2 is equivalent to E1 = E1 op E2 except that E1 is evaluated only once. [...]

关于c++ - -Wconversion warning while using operator <<= on unsigned char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29796479/

相关文章:

c++ - 为什么局部静态变量是 BSS 段的一部分?

java - Java/Android 中 |= 是什么意思? (按位或赋值)

c - 将各个位分配给字节

有人可以解释一下这个 bitCount 代码是如何工作的吗?

c -/usr/bin/ld : cannot find shared library

c - 构建交叉编译器 : Intel Xeon E5649 >>> ARMv7 with libcURL

c++ - 如何声明一个带有成员函数指针的函数

c++ - 从字符串中获取 IPv4 地址的最快方法

c++ - Rcpp:处理包含列表的列表

C++ 将 SATOSHI(uint64_t) 转换为没有 float / double 的 BTC(字符串)