Weird simple for loop runs for infinity

Hi

I don’t know why this for loop despite of break statements, is going on forever.
I am really looking for some way that explains why those 2 break statements never get executed.

Slightly modified code works fine and as expected.

Thanks in advance

When I tried to run your code, it gave me compilation error for

Q.push({0, 0, 0});

Try to change it to

node start = {0, 0, 0};
Q.push(start);

I gave a look at your code. It runs on undefined behavior, and you’re gonna facepalm yourself when I tell you why.

Look at array dx.

int dx[] = {1,1,1,-1-1,-1,0,0};

Shouldnt it be-

int dx[] = {1,1,1,-1,-1,-1,0,0};

Look at “-1” and “-1” at index 3,4 (0-based). You forgot to put a comma in between them, so essentially your array size was 7, meaning i must be from [0,6] for proper behaviour. But at i=7, it went to udnefined behavior, in this case, never executing break statements.

3 Likes

Use C++ 14.

2 Likes

Nice catch! Would love to know what exactly the compiler is making of such a situation, if someone can explain?

Compiler is making of such a situation? Most probably it will do “-1-1=-2” and store -2 in array. (Gut feeling).

If you meant run-time thing-

Cant say…atleast I cant XD

I remember once undefined behavior due to out of index exception caused code to keep on pushing elements into my vector (infinitely) resulting in SIGBRT (memory error), and I was like "WTF? I can’t declare an array of size 1000 in this Q? "

Yes it will store -2 in the array, but suppose everything works out according to the logic, then at i=7 dx[7] would access some out of bounds memory which would either work fine or result in a crash.
But here something strange is happening, which means that the compiler is optimizing the code to do something else, probably removing the i<8 and i>=8 checks. This is what I’m curious about.

I get your question. Sadly, I dont have the required knowledge. Perhaps undefined behavior tampers with execution control/line-of-execution?