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?
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.
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.
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.
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.
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With