gpt4 book ai didi

c++ - 为什么固定宽度无符号整数的输出为负,而无符号整数输出按预期回绕?

转载 作者:行者123 更新时间:2023-12-01 22:54:40 25 4
gpt4 key购买 nike

#include <iostream>

#define TRY_INT

void testRun()
{
#ifdef TRY_INT //test with unsigned
unsigned int value1{1}; //define some unsigned variables
unsigned int value2{1};
unsigned int value3{2};
#else //test with fixed width
uint16_t value1{1}; //define fixed width unsigned variables
uint16_t value2{1};
uint16_t value3{2};

#endif

if ( value1 > value2 - value3 )
{
std::cout << value1 << " is bigger than: " << value2 - value3 << "\n";
}
else
{
std::cout << value1 << " is smaller than: " << value2 - value3 << "\n";
}

}

int main()
{
testRun();

return 0;
}

使用无符号整数我得到:

1 is smaller than: 4294967295

使用固定宽度的无符号整数,输出为:

1 is smaller than: -1

我的期望是它也会环绕,这与 std::cout 有关系吗?

最佳答案

我猜是积分推广造成的。引用表格cppreference :

...arithmetic operators do not accept types smaller than int as arguments, and integral promotions are automatically applied after lvalue-to-rvalue conversion, if applicable.

unsigned char, char8_t (since C++20) or unsigned short can be converted to int if it can hold its entire value range...

因此,如果 uint16_t 只是您实现中 unsigned Short 的别名,则 value2 - value3 会使用 int< 进行计算 类型,结果也是 int,这就是显示 -1 的原因。

使用unsigned int,不会应用任何提升,并且整个计算都以此类型执行。


在最新的在线 C++ 草案中,请参阅 [conv.prom/1] :

A prvalue of an integer type other than bool, char16_­t, char32_­t, or wchar_­t whose integer conversion rank 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.

关于c++ - 为什么固定宽度无符号整数的输出为负,而无符号整数输出按预期回绕?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61056272/

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