Alex Rivera | Logout

Should I use return/continue statement instead of if-else?

Asked 2009-06-08T09:03:24.283
37

In C, C++ and C# when using a condition inside a function or loop statement it's possible to use a continue or return statement as early as possible and get rid of the else branch of an if-else statement. For example:

while( loopCondition ) {
    if( innerCondition ) {
        //do some stuff
    } else {
        //do other stuff
    }
}

becomes

 while( loopCondition ) {
    if( innerCondition ) {
        //do some stuff
        continue;
    }
    //do other stuff
}

and

void function() {
    if( condition ) {
        //do some stuff
    } else {
        //do other stuff
    }
}

becomes

void function() {
    if( condition ) {
        //do some stuff
        return;
    }
    //do other stuff
}

The "after" variant may be more readable if the if-else branches are long because this alteration eliminates indenting for the else branch.

Is such using of return/continue a good idea? Are there any possible maintenance or readability problems?

c# c++ c
Edit
Report

1 Answer

1

I generally use the if-return method when jumping out of a method or loop because there is nothing to be done.

If the body is longer because substantial work is being done, I suggest using if-else and maybe using #region to give blocks a sensible name and have them easily collapsable for people to study the control flow. That or make separate methods :)

answered 2009-06-08T09:10:43.927

Your Answer