Strange for loop behaviour

I Hate to shout out for “bug” as they are often misuse / misprogramming… So I will ask for advise before blaming the devs for mistakes that are my own.

I use C#. I want to transfer all the elements of a queue into another one. PileP1 and PileP2 are queues. I use the Count property to find out the number of elements in the queue. The section of my code creating problem is the following:

Console.Error.WriteLine("PileP1 Count = {0}", PileP1.Count);
Console.Error.WriteLine("PileP2 Count = {0}", PileP2.Count); 
Console.Error.WriteLine("CardsP1 Count = {0}", CardsP1.Count);
Console.Error.WriteLine("CardsP2 Count = {0}", CardsP2.Count);
for (int i = 0; i < PileP1.Count; i++)
{
     CardsP1.Enqueue(PileP1.Dequeue());
}
for (int i = 0; i < PileP2.Count; i++)
{
     CardsP1.Enqueue(PileP2.Dequeue());
}
Console.Error.WriteLine("after for");
Console.Error.WriteLine("PileP1 Count = {0}", PileP1.Count);
Console.Error.WriteLine("PileP2 Count = {0}", PileP2.Count); 
Console.Error.WriteLine("CardsP1 Count = {0}", CardsP1.Count);
Console.Error.WriteLine("CardsP2 Count = {0}", CardsP2.Count);

My error out looks like the following:

[…]
PileP1 Count = 5
PileP2 Count = 5
CardsP1 Count = 24
CardsP2 Count = 18
after for
PileP1 Count = 2
PileP2 Count = 2
CardsP1 Count = 30
CardsP2 Count = 18

PileP1 & P2 Count are equal to 5 before the for loops, but those are only iterated 3 times. The second weird part is that if I “hardcode” 5 in the loop

for (int i = 0; i < 5; i++)
{
    CardsP1.Enqueue(PileP1.Dequeue());
}

then I get the expected result (empty PileP queues and CardsP1 queue increased of 10.

Could someone explain this behavior not being a bug?

The test in a for loop is evaluated every iteration. So PileP1.Count and PileP2.Count are “refreshed” every loop. :smiley:

So:
Create a tmp variable

for (int i = 0, tmp=PileP1.Count; i < tmp; i++)
{
    CardsP1.Enqueue(PileP1.Dequeue());
}

Or

 for (;PileP1.Count>0 ;)
 {
     CardsP1.Enqueue(PileP1.Dequeue());
 }
1 Like

… So its definitively a bug '^^.

I thought tye condition of a for loop is calculated only once. But as we say in france, " night provides advises", i got the same suspicion overnight.

Thanks a lot for your help :smile:

EDIT: Just modified the code with an initialized tmp variable. I could submit the code with 100% success. Thanks again for the help.

Or, just use a while loop…