使用条件 ?:(三元)运算符的好处 [英] Benefits of using the conditional ?: (ternary) operator

查看:39
本文介绍了使用条件 ?:(三元)运算符的好处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与标准 if-else 语句相比,?: 运算符的优点和缺点是什么.显而易见的是:

What are the benefits and drawbacks of the ?: operator as opposed to the standard if-else statement. The obvious ones being:

条件 ?:运算符

  • 在处理直接值比较和赋值时更短、更简洁
  • 似乎没有 if/else 结构那么灵活

标准 If/Else

  • 可以应用于更多的情况(比如函数调用)
  • 通常是不必要的长

可读性似乎因声明而异.在第一次接触 ?: 操作符后的一段时间里,我花了一些时间来消化它到底是如何工作的.鉴于我与许多非程序员一起工作,您会建议尽可能使用它,还是坚持使用 if/else?

Readability seems to vary for each depending on the statement. For a little while after first being exposed to the ?: operator, it took me some time to digest exactly how it worked. Would you recommend using it wherever possible, or sticking to if/else given that I work with many non-programmers?

推荐答案

我基本上建议仅当结果语句非常短并且在不牺牲可读性的情况下显着提高了 if/else 等效语句的简洁性时才使用它.

I would basically recommend using it only when the resulting statement is extremely short and represents a significant increase in conciseness over the if/else equivalent without sacrificing readability.

>

很好的例子:

int result = Check() ? 1 : 0;

不好的例子:

int result = FirstCheck() ? 1 : SecondCheck() ? 1 : ThirdCheck() ? 1 : 0;

这篇关于使用条件 ?:(三元)运算符的好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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