gpt4 book ai didi

c++ - 将转换范围缩小到更大的类型(然后再返回)

转载 作者:太空狗 更新时间:2023-10-29 21:12:32 26 4
gpt4 key购买 nike

据我所知,从 C++11 开始,从 intunsigned long long 的转换被认为是收缩转换,因为 unsigned long long 不能表示任何负值,尽管它足够大以表示所有位。我的问题是,如果我强制转换然后转换回 int,我是否保证得到相同的值(具体意思是它既不是未定义的也不是实现定义的行为)?

int i = -42;
unsigned long long ull = static_cast<unsigned long long>(i);
int j = static_cast<int>(ull); // is this guaranteed to be -42?

此外,我想了解仅更改类型的signedness 的情况:

long long ll = -281474976710655LL;
unsigned long long ull = static_cast<unsigned long long>(ll);
long long n = static_cast<long long>(ull);

jn 是否保证与 ill 相同(分别是当然)?是否有任何需要考虑的可移植性或架构(32 位与 64 位)问题?

最佳答案

您的两个示例都是实现定义的。

有符号到无符号的转换定义明确,conv.integral/2:

If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type).

然而,无符号到有符号的转换只有定义明确,如果源值可以用目标类型表示,conv.integral/3:

If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); otherwise, the value is implementation-defined.

对于您的两个示例,无法表示源值(因为两个无符号值都大于有符号数的最大可能值),因此这些转换是实现定义的。

关于c++ - 将转换范围缩小到更大的类型(然后再返回),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47142312/

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