Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Missing return statement inside a for loop

Tags:

java

loops

return

I could find similar questions to this, but I could not find the answer that I expect to this particular case.

public int getIndex(){
    for(int x = 0; x < 5; x++) {
        return x;
    }
}

When I execute this code, I got a compilation error saying "Missing return statement". But, as per my knowledge, it is very clear that the code within the for loop will execute without any doubts due to the first time, x=0. So, there is no case not to execute the code inside the for loop for this particular case. So, why do we need to declare an extra return statement outside the for loop also?.

like image 744
Vinee-the-Pooh Avatar asked May 21 '19 12:05

Vinee-the-Pooh


3 Answers

Unlike you, the compiler is unable to (or rather, does not try to) determine that the loop executes at least once.

The specific rules around this are given in JLS 14.21. In particular:

A basic for statement can complete normally iff at least one of the following is true:

  • The for statement is reachable, there is a condition expression, and the condition expression is not a constant expression (§15.28) with value true.

  • There is a reachable break statement that exits the for statement.

The contained statement is reachable iff the for statement is reachable and the condition expression is not a constant expression whose value is false.

You don't have a constant condition expression, so, the compiler considers that such a for loop can complete normally, hence the statements after it are reachable.

It would work without a further return statement if the i < 5 were a constant expression, such as true.

public int getIndex(){
    for(int x = 0; true; x++) {
        return x;
    }
}

The compiler could determine that your original loop never completed normally, given far more complicated rules about reachability, but the practical use cases of this are so small that it would not justify the complexity.

like image 94
Andy Turner Avatar answered Nov 03 '22 06:11

Andy Turner


This is because JVM have no idea about conditional break you will use inside the loop. For example :

public static int getIndex(){
  for(int x=0; x<5;x++){
    if(x<5) continue;
    return x;
  }
  return 6;
}

Here it's clear that without a return outside the loop you could miss return statement inside loop

like image 2
PopHip Avatar answered Nov 03 '22 07:11

PopHip


I suggest that your example isn't real, But you can change it to do-while without compilation errors:

public static int getIndex() {
    int x = 0;
    do {
        return x++;         
    } while (x < 5);
}
like image 1
user7294900 Avatar answered Nov 03 '22 08:11

user7294900