Why does this code have a missing return statement error?

前端 未结 6 966
情话喂你
情话喂你 2020-12-21 00:50

If I change the else if portion of this code to an else statement it runs without any problems so I get how to make it run. What I\'m a little confused about is why I get a

6条回答
  •  攒了一身酷
    2020-12-21 01:01

    When the compiler sees else if without an else or a trailing return statement, it cannot be certain that all control paths will lead to a valid return statement.

    The compiler can be smart at times, but it can't be smart in this situation (nor should it be).

    This behavior is helpful in your example: there's absolutely no reason for you to use an else if in this situation. A simple else is easier to read, more concise, and less error prone.

    An else is very expressive in this case. It means "the opposite of the if clause" which will still be the case if the code changes in the future.

    Your current code would be more likely to contain and/or introduce a bug if the compiler allowed it.

    Here's how I would rewrite the method body:

    if (negative) {
        return (a < 0 && b < 0);
    }
    else {
        return (a < 0 && b > 0) || (a > 0 && b < 0);
    }
    

    In general you should prefer if (negative) over if (!negative) unless there's a compelling reason (ie readability) to do otherwise.

    Also, a lot of people (including myself) try to put the most simple clause first in an if/else statement. Making your code easy to read is a good thing.

    Check out StephenC's answer for a technical explanation and more background about why the compiler behaves this way.

提交回复
热议问题