有条件的经营者VS如果当时其他 [英] Conditional operator vs if then else
问题描述
如果我要实现一些条件code,可以在两者的方式来实现。那么哪种方式更好条件运算符:或if..then..else ??
If I want to implement some conditional code that can be implemented in both of the ways. Then which way is better conditional operator ?: or if..then..else??
推荐答案
这要看情况。一般情况下,你想活动的主要流程
是在code的结构psented重新$ P $。如果关键点
该算法是变量 X
初始化,然后
最好的解决办法是使用条件运算符:
It depends. In general, you want the major flow of activity to
be represented in the structure of the code. If the key point
of the algorithm is that the variable x
is initialized, then
the best solution is to use the conditional operator:
x = condition ? f1() : f2();
如果决定是至关重要的问题对于理解是什么
怎么回事,然后你就会preFER的如果
。在实践中,这意味着
当两者都是合理的可能,你会使用:
。该
键为合理—如果你发现你正在使用的
逗号操作符在SUBEX pressions的SUBEX pressions有
副作用,然后用:
很可能不是合理。
If the decision is the critical issue for understanding what is
going on, then you'll prefer the if
. In practice, this means
that when both are reasonably possible, you'll use ?:
. The
key being "reasonably"—if you find that you're using the
comma operator in the subexpressions, of the subexpressions have
side effects, then using ?:
is probably not "reasonable".
当你使用:
运营商,但在所有的最简单
的情况下,你应该确切地格式化它,你会在如果
,例如:
When you do use the ?:
operator, in all but the simplest
cases, you should format it exactly as you would an if
, e.g.:
x = condition
? complex_expression_1
: complex_expression_2;
我经常这样做。 (有一个特殊的情况下我会推
它:如果我可以向下降低整个功能单一的回报
声明。我仍然不会允许逗号的副作用
运营商,但我有时会用更复杂的前pressions
比我原本可以达到的。)
I do this regularly. (There's a special case where I'll push it: if I can reduce the entire function down to a single return statement. I still won't allow side effects of the comma operator, but I will sometimes use more complicated expressions than I otherwise would.)
这篇关于有条件的经营者VS如果当时其他的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!