c++ - static_cast<int>(long long) 安全吗?

标签 c++ casting

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, and long 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/

相关文章:

c++ - 正确获取 sizeof()

c++ - 将一个 constexpr 数组初始化为其他两个 constexpr 数组的总和

无法使用 atoi() 将 char 数字转换为 int

c# - 从具有未知签名的 MethodInfo 创建表达式函数

java - 为什么 java 在...复杂时返回 java.util.LinkedHashMap

c++ - 带有预定义(枚举)选项列表而不是单个参数的 api 扩展的缺点

c++ - 将类对象传递给函数(可能通过指针而不是引用)C++

c++ - Boost Spirit X3 eol 意外行为

c# - 用更好的图案替换铸件

c++ - 动态转换还是函数重载?