gpt4 book ai didi

c++ - 用提升解释整数比较

转载 作者:IT老高 更新时间:2023-10-28 23:02:13 24 4
gpt4 key购买 nike

我试图了解整数提升和比较在 C++ 应用程序中的工作原理。

#include <cstdint>

int main(void)
{
uint32_t foo = 20;
uint8_t a = 2;
uint8_t b = 1;
uint8_t c = 5;

if(foo == b*c) {}

if(foo == a) {}

if(foo == a + c) {}

if(foo == a + b*c) {}

return 0;
}

仅在最后一次比较时,我会收到编译器警告:“有符号和无符号整数表达式之间的比较 [-Wsign-compare]”。

为什么这只发生在最后一种情况,而其他情况没有?

最佳答案

由于操作数的类型不同,因此会进行一组隐式转换以达到通用类型。

For the binary operators (except shifts), if the promoted operands have different types, additional set of implicit conversions is applied, known as usual arithmetic conversions with the goal to produce the common type (also accessible via the std::common_type type trait)

因为这里的整数类型整数转换适用于:

  • If either operand has scoped enumeration type, no conversion is performed: the other operand and the return type must have the same
    type
    • Otherwise, if either operand is long double, the other operand is converted to long double
    • Otherwise, if either operand is double, the other operand is converted to double
    • Otherwise, if either operand is float, the other operand is converted to float
    • Otherwise, the operand has integer type (because bool, char, char8_t, char16_t, char32_t, wchar_t, and unscoped enumeration were promoted at this point) and integral conversions are applied to produce the common type, as follows:
    • If both operands are signed or both are unsigned, the operand with lesser conversion rank is converted to the operand with the greater integer conversion rank
    • Otherwise, if the unsigned operand's conversion rank is greater or equal to the conversion rank of the signed operand, the signed operand is converted to the unsigned
      operand's type.
    • Otherwise, if the signed operand's type can represent all values of the unsigned operand, the unsigned operand is converted to the signed operand's type Otherwise, both operands are converted to the unsigned counterpart of the signed operand's type.

相同的算术转换适用于 comparison operators也是。

从这一切可以得出结论,因为 rhs 都是 uint8_t 通用类型将是 int,然后由于 rhsuint32_t == 运算符的常见类型将是 uint32_t。但由于某种原因,我不知道 gcc 不会在 clang 进行最后一次转换时进行。参见 godblot+ 运算符的 gcc 类型转换也可能发生警告是错误警告并且发生转换的情况,就像 + 运算符发生的那样。看看 clang 如何看到最后一个 if( cppinsights ):

if(foo == static_cast<unsigned int>(static_cast<int>(a) + (static_cast<int> 
(b) * static_cast<int>(c))))

更新:

我在两个编译器生成的程序集中找不到差异,我同意 @M.M 所以,IMO 这是一个 gcc 错误。

关于c++ - 用提升解释整数比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56796877/

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