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

Problem Description:

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.

**Question**: What happens to each kind of integer and integer-multiplication in my subscript operator of `arr’ when I access it with the following:

```
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. 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. 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.

## Solution – 1

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`

.

If `B + A`

overflows `int`

, `B + A + N`

will cause you problems that don’t exist with `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.