I was trying to make a 'smart' optimization when I stumbled upon some weird behavior, so I created a minimal example to replicate it.
In the code below, I create an array and shift elements to the left, then print the array. The code works exactly like one would expect.
#include <iostream>
int main()
{
int array[5]{0,1,2,3,4};
for (int i = 0; i < 4; ++i)
{
array[i] = array[i + 1]; // Array becomes {1,2,3,4,4}
}
std::cout << "Printing array: ";
for (int i = 0; i < 5; ++i)
{
std::cout << array[i]; // Prints {1,2,3,4, 4}
}
std::cout << "\n";
}
Now, looking at the first for
block, I thought I could spare one i
increment.
So I tried to rewrite that block as follows:
for (int i = 0; i < 4;)
{
array[i] = array[++i]; // Expected: array becomes {1,2,3,4,4}
}
This does not work, however.
i
is in fact updated, because the program does not loop, but the assignment does not go as expected and the terminal outputs Printing array: 01234
.
Now, it might have been that the expression on the right is evaluated before the expression on the left, in which case this behavior would be explained. However, I also tried the following reverse iteration:
for (int i = 4; i > 0;)
{
array[--i] = array[i]; // Expected: array becomes {1,2,3,4,4}
}
And it also outputs Printing array: 01234
.
In both cases, I tried compiling in debug mode, in case it was some weird compiler optimization responsible for it, but the result was still the same.