c++ - 为什么一元运算符返回的类型与其操作数不同?

标签 c++ return-type unsigned unary-operator

看起来 uint16_t 和 uint8_t 上的一元按位非运算符 (~) 返回 int, 而不是其操作数的类型(与一元 - 相同)。 有人可以说明为什么会这样吗?

令人惊讶的是 ~uint16_t(0) < uint16_t(0)

我使用的是 g++ 版本 9.2.1 20191008 (Ubuntu 9.2.1-9ubuntu2) x86_64-linux-gnu

最佳答案

来自 C++11 Standard 5.3.1.8:

The operand of the unary - operator shall have arithmetic or unscoped enumeration type and the result is the negation of its operand. Integral promotion is performed on integral or enumeration operands. The negative of an unsigned quantity is computed by subtracting its value from 2^n, where n is the number of bits in the promoted operand. The type of the result is the type of the promoted operand.

所以它指出整数提升发生在一元运算符上。

关于c++ - 为什么一元运算符返回的类型与其操作数不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60587449/

相关文章:

vb6 - VB6是否支持无符号数据类型?

c++ - 任意长度的 BINARY 类型的 QT SQL 数据类型 (QVariant) 映射

c++ - OpenCV - 如何捕获rtsp视频流

c++ - 如何在 header 和 .cpp 文件中正确声明返回自己定义类型的函数?

python - 如何在python中将有符号整数转换为无符号整数

c++ - 如何从 payload unsigned char buf 获取 IP 和 PORT?

c++ - 我如何在 C++ 中使用 std::optional?

c++ - STL vector 和指向 vector 元素的指针

c++ - 为什么 C++ 中的 main() 函数不采用除 int 和 void 以外的任何其他返回类型

java - Play Framework AJAX 在 badRequest() 处返回对象