Reputation: 83
I am getting compile time "unreachable code" error on below line in my program:
System.out.println("i =" + i + ", j = " + j);
public static void main(String[] args) {
int i = 0, j = 5;
tp: for (;;)
{
i++;
for (;;)
{
if (i > --j) {
break tp;
}
}
System.out.println("i =" + i + ", j = " + j);
}
}
kindly help me out to find the exact cause for this. Thanks in advance.
Upvotes: 2
Views: 222
Reputation: 17597
The inner loop is an infinite loop. The only way to exit it is when i > --j
is true, but this will break the outer loop (due to the call of break tp;
) and the program will immediately execute the next code after the outer loop. That means there is no condition where the inner loop terminates "normally" so the next code after it can run.
Upvotes: 1
Reputation: 85799
Let's analyze this code:
tp: for (;;) //<-- similar to while(true)
{
i++; //increases i by 1
for (;;) //<-- similar to while(true)
{
if (i > --j) { //decreases j and compares its value against i
break tp; //breaks tp, which means breaking the outer for loop
}
}
//while(true) above
//if break gets executed, it breaks this for loop
//so this line can never be executed
System.out.println("i =" + i + ", j = " + j);
}
Easiest solution:
Move System.out.println("i =" + i + ", j = " + j);
outside the outer for
loop.
tp: for (;;)
{
i++;
for (;;)
{
if (i > --j) {
break tp;
}
}
}
System.out.println("i =" + i + ", j = " + j);
Upvotes: 7
Reputation: 178343
The System.out.println
code can't be reached ever, even if i
is greater than j
. The only break
sends you breaking
out of the outer for
loop. The System.out.println
statement is after the inner for
loop, but in the inner for
loop, you either keep looping, decrementing j
, or you break
the outer loop
. There is no way to reach the println
statement.
To print what i
and j
are after the loop ends, move the System.out.println
call after the ending brace of the outer for
loop.
Upvotes: 3