Difference in a C++ pointer behavior when incremented in the for loop definition vs inside for loop
A
for (init-statement; condition; iteration-expression)
{
dostuff();
}
maps to
{
init-statement
while ( condition )
{
dostuff();
iteration-expression ;
}
}
so we get
{
slow = head, fast = head;
while (fast && fast->next)
{
slow = slow->next, fast = fast->next->next;
dostuff(); // for example purposes only. Not really replacible with a function
}
}
and
{
slow = head, fast = head;
while (fast && fast->next)
{
dostuff();
slow = slow->next, fast=fast->next->next;
}
}
In the first, slow
and fast
are always updated before dostuff()
.
In the second, dostuff
happens before slow
and fast
are updated, so the values of slow
and fast
used in dostuff
will be different on the first loop iteration.