Alireza Peer
Alireza Peer

Reputation: 908

for loop iterator suddenly changes

here is my method, its just a nested loop:

IEnumerator startNewRound()
{
    string st = "آبپتثجچحخدذرضطظعغفقکگلمنوهی";
    for (int i = 0; i < st.Length; i++)
    {
        for (int j = i + 1; i < st.Length; j++)
        {
            for (int z = j + 1; z < st.Length; z++)
            {
                if (z > st.Length) continue;
                yield return new WaitForSeconds(0.1f);
                Debug.Log("I = " + i + " J = " + j + " Z= " + z);
            }
        }
    }
}

suddenly inside the loop program freezes for some seconds and, 'j' counter changes and every thing blows up! here is my Log:

enter image description here

I cant understand what is wrong!

Upvotes: 0

Views: 95

Answers (1)

Jamiec
Jamiec

Reputation: 136074

In your second nested loop, you mistakenly use i instead of j as the loop control variable:

for (int j = i + 1; i < st.Length; j++)

Should be

for (int j = i + 1; j < st.Length; j++)

Why does this cause a problem? Lets look at the pertinent part of the utput:

I = 0 J = 24 Z= 25
I = 0 J = 24 Z= 26
I = 0 J = 25 Z= 26
I = 0 J = 2147483647 Z= -2147483648
I = 0 J = 2147483647 Z= -2147483647
I = 0 J = 2147483647 Z= -2147483646

At the point that your code hits I=0, J=25 & z=26 (which is one less than the length of st) the following happens:

  • z gets incremented to 27
  • The test in the 3rd loop checks z < st.Length and thus ends that loop
  • j gets incremented to 26
  • The third loop initialises z to j+1 (27)
  • The third loop evaluates z < st.Length - false. Exit the loop without ever entering it to output anything
  • The second loop evaluates i < st.Length - true and enters the loop.
  • After that loop j is incremented
  • continue ad infinitum until integer overflow

Upvotes: 11

Related Questions