Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

c#

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?

like image 967
sharptooth Avatar asked Jun 08 '09 09:06

sharptooth


People also ask

Should I use if else or return?

It depends on the semantics of your code, if the else branch is the point of the method, i.e. it's named after what happens in the else branch, the early return is probably correct, especially if the first part is some sort of check.

Why we should not use continue?

If you use continue then it means your loop elements are not restricted enough, so there is the potential you are looping through unnecessary elements. It also means that at any point inside a loop, you break the 'rules' of the loop. So any change at a later date may break things if you do not notice a continue.

Can Continue statement be used in if else?

The continue statement skips the current iteration of the loop and continues with the next iteration. Its syntax is: continue; The continue statement is almost always used with the if...else statement.

Is continue faster than else?

No, there's no speed advantage when using continue here. Both of your codes are identical and even without optimizations they produce the same machine code. However, sometimes continue can make your code a lot more efficient, if you have structured your loop in a specific way, e.g.


1 Answers

My personal approach of choosing one is that if the body of the if part is very short (3 or 4 lines maximum), it makes sense to use the return/continue variant. If the body is long, it's harder to keep track of the control flow so I choose the else version.

As a result, normally, this approach limits the usage of return/continue style to skip some data and avoid further processing rather than process this using one of the following methods (which is better suited by if/else).

like image 91
mmx Avatar answered Oct 06 '22 05:10

mmx