Why would this compile much less work?

I made a typo in a piece of code which mysteriously made it work. I don't think it should even compile, much less work. I'm stumped.

I was trying to debug the loop below and figure out why the BoardLoc assignment never seemed to execute. I put in the cout to help me debug. The cout didn't execute either. No surprise there given that the assignment wasn't happening, but I couldn't see any reason why both wouldn't work. Previous couts told me all the indexes were valid and correct: i was 2, j was 3, and k was 4. So the loop should execute once with m at 3 and be done with it, right?

1
2
3
4
5
   for(m=k-1; m==i; m--)
      {
      BoardLoc[m][j]=ThisMove; //Back it up and flip the tiles.
      cout<<"m: "<<m<<endl<<endl;
      }


While futzing around with this I added a stray semi-colon after the for expression by mistake:

1
2
3
4
5
   for(m=k-1; m==i; m--)
      ;{
      BoardLoc[m][j]=ThisMove; //Back it up and flip the tiles.
      cout<<"m: "<<m<<endl<<endl;
      }


Now it works! The assignment happens and the cout of the m works.

But why on earth? Shouldn't the first semi-colon break the compile?
These statements are no longer part of the for loop.
1
2
      BoardLoc[m][j]=ThisMove; //Back it up and flip the tiles.
      cout<<"m: "<<m<<endl<<endl;




The for loop executes but does nothing. Then the statements above execute.
The for loop executes but does nothing. Then the statements above execute.


Ah, that makes perfect sense. But that puts me back at square one. Given the values of the indexes I specify above, shouldn't the first example code execute once with m==3?
The original for loop will execute once if k == i+1. Otherwise it won't execute at all. Do you have the loop parts right? You are initializing to k-1, but comparing it to i. What is the relationship between k and i?
Ah, that makes perfect sense. But that puts me back at square one. Given the values of the indexes I specify above, shouldn't the first example code execute once with m==3?



if m == 3 and i == 2 then the loop condition m == i is false.
Last edited on
Oh. Duh. No, I'm an idiot.

The loop condition was wrong. It should be like this:

1
2
3
4
5
for(m=k-1; m>i; m--)
        {
        BoardLoc[m][j]=ThisMove; //Back it up and flip the tiles.
        cout<<"m: "<<m<<endl<<endl;
        }
Topic archived. No new replies allowed.