要三元还是不三元? [英] To ternary or not to ternary?

查看:112
本文介绍了要三元还是不三元?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我个人是三元运算符的拥护者:()? :;我确实意识到它有它的位置,但是我遇到了许多完全反对使用它的程序员,有些人经常使用它.

I'm personally an advocate of the ternary operator: () ? : ; I do realize that it has its place, but I have come across many programmers that are completely against ever using it, and some that use it too often.

您对此有何感想?您看到过使用它有趣的代码吗?

What are your feelings on it? What interesting code have you seen using it?

推荐答案

仅将其用于简单表达式:

int a = (b > 10) ? c : d;

不要链或嵌套三元运算符,因为它难以阅读和造成混淆:

Don't chain or nest ternary operators as it hard to read and confusing:

int a = b > 10 ? c < 20 ? 50 : 80 : e == 2 ? 4 : 8;

此外,在使用三元运算符时,请考虑以提高可读性的方式对代码进行格式化:

Moreover, when using ternary operator, consider formatting the code in a way that improve readability:

int a = (b > 10) ? some_value                 
                 : another_value;

这篇关于要三元还是不三元?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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