我应该使用收益/ continue语句代替的if-else? [英] Should I use return/continue statement instead of if-else?

查看:424
本文介绍了我应该使用收益/ continue语句代替的if-else?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C,C ++和C#中使用函数或循环语句有可能使用的继续内部条件时收益的声明尽早和摆脱一个的的if-else 的语句的其他的分支。例如:

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
    }
}

变为

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

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

变为

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

本经如果的if-else分支是长,因为这种改变消除了缩进else分支变异可能更容易阅读。

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?

推荐答案

编译器几乎肯定会产生相同的code。即使它没有,差别很可能是无关紧要的。因此,相关的说法是肯定的人会怎么看它。

The compiler will almost certainly generate the same code. Even if it didn't, the difference will be probably irrelevant. Hence, the relevant argument is certainly how people would read it.

因此​​,问题是如何类似的//做一些东西和做其他的东西是。如果他们是概念上相似,使用的if / else。如果他们是不同的概念,继续使用/返回。

Therefore the question is how similar "//do some stuff" and "do other stuff" are. If they are conceptually similar, use if/else. If they're conceptually different, use continue/return.

这篇关于我应该使用收益/ continue语句代替的if-else?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆