问题描述
我遇到了执行以下转换的代码:
I've encountered code that performs the following conversion:
static_cast< unsigned long>( - 1)
据我所知,C ++标准定义了将有符号整数值转换为无符号整数类型时发生的情况(参见:如果我为一个无符号变量赋值一个负值,会发生什么? a>)。
As far as I can tell, the C++ standard defines what happens when converting a signed integer value to an unsigned integral type (see: What happens if I assign a negative value to an unsigned variable?).
上述代码中的问题是源和目标类型可能有不同的大小,并且这是否会对结果产生影响。编译器会在放置之前放大源值类型吗?它会转而转换为相同大小的无符号整数,然后放大?
The concern I have in the above code is that the source and destination types may be different sizes and whether or not this has an impact on the result. Would the compiler enlarge the source value type before casting? Would it instead cast to an unsigned integer of the same size and then enlarge that? Or perhaps something else?
若要澄清代码,
int nInt = -1;
long nLong = -1; // assume sizeof(long) > sizeof(int)
unsigned long res1 = static_cast<unsigned long>(nInt)
unsigned long res2 = static_cast<unsigned long>(nLong);
assert(res1 == res2); // ???
基本上,我应该担心编写代码
Basically, should I be worrying about writing code like
static_cast<unsigned long>(-1L)
static_cast<unsigned long>(-1)
推荐答案
从C ++ 11标准4.7积分转换,第2段:
From the C++11 standard, 4.7 "Integral conversions", para 2:
换句话说,当转换为无符号整数,只有输入的值重要,不是它的类型。将-1转换为n位无符号整数将始终给出2 -1,无论-1作为哪个整数类型。
In other words, when converting to an unsigned integer, only the value of the input matters, not its type. Converting -1 to an n-bit unsigned integer will always give you 2-1, regardless of which integer type the -1 started as.
这篇关于将负整数转换为较大的无符号整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!