我想执行以下操作:
if(x == true)
{
// do this on behalf of x
// do this on behalf of x
// do this on behalf of x
}
使用条件运算符,这样正确吗?
x == true ? { /*do a*/, /*do b*/, /*do c*/ } : y == true ? ... ;
这是畸形的吗?
我没有使用条件运算符嵌套超过一层。
我打算使用的表达式非常简洁和简单,使条件运算符在我看来值得使用。
附言我不是在问 A。我应该使用哪个? B. 哪个更好 C. 哪个更合适
附言我在问如何将 if-else 语句转换为三元条件运算符。
就此问题给出的有关编码标准等的任何建议都是不受欢迎的。
最佳答案
不要将 bool 值与 true 和 false 进行比较。没有意义,因为它们已经是真或假了!随便写
if (x)
{
// do this on behalf of x
// do this on behalf of x
// do this on behalf of x
}
您的第二个示例无法编译,因为您使用了 {
和 }
。但这可能
x ? ( /*do a*/, /*do b*/, /*do c*/ ) : y ? ... ;
但这确实取决于 /*do a*/
等是什么。
关于c++ - 条件运算符 : How much flexibility?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16191461/