为什么固定宽度无符号整数的输出为负数,而无符号整数的输出如预期那样回绕?

问题描述 投票:2回答:2
#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

具有固定宽度的unsigned int,输出为:

1 is smaller than: -1

我期望它也可以环绕,这与std :: cout有关系吗?

c++ unsigned-integer
2个回答
1
投票

[unsigned int等效于uint32_tunsigned short int等效于uint16_t


1
投票

我想这是由整体促销

© www.soinside.com 2019 - 2024. All rights reserved.