如何正确使用三元运算符 [英] How to correctly use the ternary operator

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

问题描述

鉴于以下两个语句,有人可以帮助我仅使用三元运算符而不是if语句吗?

Given the the below two statements, could someone help me use only the ternary operator instead of if statements?

我已经做了很多尝试:

if(strstr(cv[i],a.c_str()))
{
    o=1;
    p=cv[i];
    p=p.substr(a.size()+1);
}
else o+=4;

if (b^*s && c++ + 1 ^ *s)
{
    cout << b;
    if (b^--c)
        cout << (c - b>1 ? "-" : ",") << c;

    if (a)
        cout << ",";
    b = c = *s;
}

推荐答案

三元运算符是一个表达式,在求值时会返回一个值:

The ternary operator is an expression, which returns a value when evaluated:

<result> = <condition> ? <when true> : <when false>

在此伪代码中,<when true><when false>也必须是表达式.尽管您可以通过一些技巧将多个语句打包到单个表达式中(例如,使用do { <statements> } while(false);结构将其包含在内),但三元运算符并不打算用于此.当thenelse分支均由单个语句组成时,应使用三元运算符,并且可以选择使用表达式的返回值.

In this pseudo code <when true> and <when false> must also be an expression. Although you can pack several statements into a single expression with some trick (e.g. to embrace it with a do { <statements> } while(false); structure), the ternary operator is not meant to be used for this. You should use a ternary operator when both the then and the else branches are consisted of a single statement, and optionally you may use the return value of the expression.

所以举一个非常简单的例子,而不是写

So to take a very simple example, instead of writing

if(x > 0)
  y += 10;
else
  y += 20;

使用三元运算符更干净,更简单:

It is cleaner and simpler to use a ternary operator:

y += x > 0 ? 10 : 20;

但是条件分支包含多个语句却不是这种情况,因为在这种情况下,使用三元运算符只会使您的代码看起来更加混乱和难以理解.

However it is not the case when the conditional branches contain multiple statements, as in that case the use of a ternary operator would just make your code look more confusing and harder to understand.

这篇关于如何正确使用三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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