Closed
Description
Consider the following code:
#include <limits.h>
int A[2][2] = {
{ INT_MAX, INT_MAX },
{ INT_MIN, INT_MIN },
};
int f(void) {
int sum = 0;
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
sum += A[j][i];
return sum;
}
In the original code, sum
is calculated as follows:
(i, j) | sum
-------|--------------------
(0, 0) | INT_MAX
(0, 1) | -1
(1, 0) | INT_MAX - 1
(1, 1) | -2
On the other hand, if they are interchanged, the calculation proceeds as shown below, resulting in signed integer overflow:
(i, j) | sum
-------|--------------------
(0, 0) | INT_MAX
(1, 0) | INT_MAX + INT_MAX
...
Currently, such an interchange can be applied in some cases.
godbolt: https://godbolt.org/z/oqYs14va9