简体   繁体   中英

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;
        }
    }
}

Because i++ is never executed. break inside a loop means "leave the loop immediately." Both branches of your if / else have it, so both break out of the loop on the first iteration, and the i++ part of the for never gets a chance to run. The for loop may as well be simply int i = 0; followed by the code currently in the loop body (without break; s), if you don't intend to loop.

Presumably, you're looping for a reason, and at most only one of those blocks should have the break .

The problem is not that you have a break , but that you have two of them. Both of the break s 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.

Your code is incomplete but I can still identify where is the issue at... you have this for loop and inside of it an if-else ...

if you look carefully there is something peculiar in that if else:

if the condition is met you break the loop but if the condition is not met you break the loop too...

that means no matter if this is true or not ElsoJatekos.elsoJatekosCsapata[i] == 0 you will break the loop and ALL that is written after the if-else becomes dead-code...

you will never executed... the IDE is smart enough to figure out that...

that is the reason why the IDE is complaining....

public static void harcos1csapatbaHelyez()
        {
        for (int i = 0; i < 7; i++) {
            if (ElsoJatekos.elsoJatekosCsapata[i] == 0) {
                ElsoJatekos.elsoJatekosCsapata[i] = 1;
                break;  
            } else {
                System.out.println("Elérted a maximális csapatlétszámot!");
                break;
            }

        //
        // something else here that is dead-code
        }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM