[英]What happens when accessing an array with multiple different types: int16_t, int, and int64_t, in C++?
Suppose I have a dynamically allocated array as in假设我有一个动态分配的数组,如
int64_t * arr; arr = new int64_t[M];
where M is of type int64_t and is large enough to handle the accessed value I show below in the subscript operator.其中 M 是 int64_t 类型并且足够大以处理我在下标运算符中显示的访问值。
Question : What happens to each kind of integer and integer-multiplication in my subscript operator of `arr' when I access it with the following:问题:当我使用以下内容访问 ‘arr’ 的下标运算符时,每种 integer 和整数乘法会发生什么情况:
int16_t A = 12;
int B = INT_MAX;
int64_t N = int64_t(B)*int64_t(B) // This will store the correct value of 800^3 into N and will not cause wrap-around
int64_t my_value = arr[N + B + A]
int64_t my_value_2 = arr[A + B + N]
int64_t my_value_3 = arr[B]
int64_t my_value_4 = arr[12L*(Nx+Nx*Ny+1)]
? ?
I am unsure of the rules for these different integer types are handled in the subscripting operator.我不确定这些不同的 integer 类型的规则是在下标运算符中处理的。 I am familiar with working with subscripting operators where all variables used in the operator are all of type `int' and are small enough that they will not overflow.
我熟悉使用下标运算符,其中运算符中使用的所有变量都是“int”类型并且足够小以至于它们不会溢出。 I'm unsure of the behavior when there are multiple int types all called in the same operator, especially for large arrays where int64_t is required.
当在同一个运算符中调用多个 int 类型时,我不确定行为,尤其是对于需要 int64_t 的大型 arrays。
The addition operator ( +
) is left-to-right associative.加法运算符 (
+
) 是从左到右结合的。 As a result, given结果,给定
int16_t A;
int B;
int64_t N;
then N + B + A
and B + A + N
both have the same final result type, but the former uses int64_t
(or int
, if it is larger) to compute the subexpression N + B
and the latter uses int
(which cannot be smaller than int16_t
) to compute the subexpression B + A
.那么
N + B + A
和B + A + N
都有相同的最终结果类型,但前者使用int64_t
(或int
,如果它更大)来计算子表达式N + B
而后者使用int
(这不能是小于int16_t
) 来计算子表达式B + A
。
If B + A
overflows int
, B + A + N
will cause you problems that don't exist with N + B + A
.如果
B + A
溢出int
, B + A + N
将导致N + B + A
不存在的问题。
Note that INT_MAX
can be 2 15 -1, 2 31 -1, 2 63 -1 (among other legal values) and therefore it is not portable to assume that int64_t(INT_MAX)*int64_t(INT_MAX)
does not overflow.请注意,
INT_MAX
可以是 2 15 -1、2 31 -1、2 63 -1(以及其他合法值),因此假设int64_t(INT_MAX)*int64_t(INT_MAX)
不溢出是不可移植的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.