In my current project I stumbled upon a weird phenomenon where a nested for-loop would only execute the inner loop once and then simply stop. Even after careful inspection of all variables involved, the outer for-loop still terminated without due reason. The only thing that made this construction different from other for-loops contained in my program was the fact that the counter variable was passed as a parameter to the function containing the loop and never copied anywhere.
So I decided to test if the problem can be reproduced:
#include <stdio.h>
void someFunction(int x, int y, int width, int length)
{
int endX = x+width;
int endY = y+length;
printf("x will not exceed: %i\n", endX);
printf("y will not exceed: %i\n", endY);
for(; x < endX; x++)
{
for(; y < endY; y++)
{
printf("(%i, %i)\n", x, y);
}
}
}
int main(int argc, const char *argv[])
{
someFunction(1, 1, 5, 5);
return 0;
}
Upon execution, however, the output of the application differs from intuitive expection:
x will not exceed: 6
y will not exceed: 6
(1, 1)
(1, 2)
(1, 3)
(1, 4)
(1, 5)
The behavior is similar when x and y are switched, but with the y variable never being incremented. The problem is solved by simply declaring a new variable as the counter for each of the loops.
But why does this happen? Is it disallowed for a specific reason? Does the compiler disable modification of certain parameters and if so, why does it work with one variable but not the other?
The source code provided was compiled with GCC/G++ 4.5.3 without any special optimization flags.
yis never being reset within thexloop, so once it goes out of bounds on the first pass it stays out of bounds forevermore.