Richard Townley
Richard Townley

Reputation: 23

Returning inside an else statement

Should you write your functions like this:

int foo()
{
    if (bar)
        return 1;
    return 2;
}

Or like this?

int foo()
{
    if (bar)
        return 1;
    else
        return 2;
}

Is one way objectively better than the other, or is it a matter of personal preference? If one way is better, why?

Upvotes: 0

Views: 149

Answers (3)

RJM
RJM

Reputation: 1178

I try to have one exit point from a function whenever possible. Makes the code more maintainable and debugable. So I'd do something like this:

int foo()
{
    var retVal;
    if (bar) {
        retVal = 1;
    }
    else {
        retVal = 2;
    }
    return retVal;
}

Or this if you want to be more concise...

int foo()
{
    var retVal = 2;
    if (bar) {
        retVal = 1;
    }
    return retVal;
}

Upvotes: 1

Rajshekar Reddy
Rajshekar Reddy

Reputation: 18997

Nothing different in the matter of performance. Here Its personal preference. I prefer the second one as it is clean and understandable. Experienced folks can grasp both the syntax right away But when you place the first syntax in front of a new programmer he will get confused.

I prefer neat code (keeping into account both readability and performance). When there is certainly no performance improvement with the first syntax I would choose second syntax.

Upvotes: 1

Baahubali
Baahubali

Reputation: 4802

there is no performance improvement in any of the statements above and totally your choice. compiler is smart enough to figure out what you are trying to do. personally i prefer the first one because that means less code. however in c#, msil generated will be the same for both scenarios.

Upvotes: 0

Related Questions