gpt4 book ai didi

c++ - 将 unsigned int 的最大值转换为 int 并期望结果为 -1 是否可移植?

转载 作者:行者123 更新时间:2023-12-01 22:34:15 24 4
gpt4 key购买 nike

我发现了一个 C++ 代码,其中我们将初始化为最大值的 unsigned int 32 转换为有符号 int,并期望它为 -1。它在经过测试的编译器上运行良好,但它真的可移植吗?

int GetBusinessDataID()
{
u32_t id = ~0;

// Some code that may return a valid ID.

return id; // Here we expect to return -1.
}

最佳答案

这对于 integral conversions 是有保证的自 C++20 起;在 C++20 之前,这是实现定义的。

If the destination type is signed, the value does not change if the source integer can be represented in the destination type. Otherwise the result is

  • implementation-defined (until C++20)

  • the unique value of the destination type equal to the source value modulo 2nwhere n is the number of bits used to represent the destination type. (since C++20).

关于c++ - 将 unsigned int 的最大值转换为 int 并期望结果为 -1 是否可移植?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59625590/

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