Search code examples
javadead-code

Why i get dead code warnig if there is a break in the for loop?


public static void harcos1csapatbaHelyez()
{
    for (int i=0 ; i<7 ; i++)
    {
        if (ElsoJatekos.elsoJatekosCsapata[i] == 0)
        {
            ElsoJatekos.elsoJatekosCsapata[i] = 1;

            break;  //If i dont remove it, it will cause a dead code warning and the for loop will be execute just once! How can I jump out from this loop otherwise?
        }
        else
        {
            System.out.println("Elérted a maximális csapatlétszámot!");
            break;
        }
    }
}

Solution

  • The problem is not that you have a break, but that you have two of them. Both of the breaks are located in opposite branches of a conditional if statement, which amounts to an unconditional break. No matter what side of the if your code takes, there's a break at the end.

    This means that the i++ statement from the loop header will never get executed; that is your dead code.