繁体   English   中英

在 C++ 中访问具有多种不同类型的数组时会发生什么:int16_t、int 和 int64_t?

[英]What happens when accessing an array with multiple different types: int16_t, int, and int64_t, in C++?

假设我有一个动态分配的数组,如

int64_t * arr; arr = new int64_t[M];

其中 M 是 int64_t 类型并且足够大以处理我在下标运算符中显示的访问值。

问题:当我使用以下内容访问 ‘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)]

我不确定这些不同的 integer 类型的规则是在下标运算符中处理的。 我熟悉使用下标运算符,其中运算符中使用的所有变量都是“int”类型并且足够小以至于它们不会溢出。 当在同一个运算符中调用多个 int 类型时,我不确定行为,尤其是对于需要 int64_t 的大型 arrays。

加法运算符 ( + ) 是从左到右结合的。 结果,给定

int16_t A;
int B;
int64_t N;

那么N + B + AB + A + N都有相同的最终结果类型,但前者使用int64_t (或int ,如果它更大)来计算子表达式N + B而后者使用int (这不能是小于int16_t ) 来计算子表达式B + A

如果B + A溢出intB + A + N将导致N + B + A不存在的问题。


请注意, 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM