是static_cast<int>(long long)
安全(保证行为)?
或者我应该static_cast<int>(val & 0xffffffffLL)
第一?
最佳答案
它是安全的,但是,它可能是实现定义的。
首先,
4.8 Integral conversions [conv.integral]
1 A prvalue of an integer type can be converted to a prvalue of another integer type. A prvalue of an unscoped enumeration type can be converted to a prvalue of an integer type.
3 If the destination type is signed, the value is unchanged if it can be represented in the destination type; otherwise, the value is implementation-defined.
现在,
3.9.1 Fundamental types [basic.fundamental]
2 There are five standard signed integer types :
signed char
,short int
,int
,long int
, andlong long int
. In this list, each type provides at least as much storage as those preceding it in the list. There may also be implementation-defined extended signed integer types. The standard and extended signed integer types are collectively called signed integer types. Plain ints have the natural size suggested by the architecture of the execution environment46; the other signed integer types are provided to meet special needs.46)
int
must also be large enough to contain any value in the range[INT_MIN, INT_MAX]
, as defined in the header<climits>
.
这意味着 long long
至少和int
一样大.如果它们大小相同,则它们之间的转换没有任何作用。如果long long
更大,它是实现定义的,但我从来没有见过一个实现,除了首先采取 n
之外还会做其他事情根据大小的字节数。
关于c++ - static_cast<int>(long long) 安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39683781/