简体   繁体   English

具有多个语句的三元运算符

[英]Ternary operator with multiple statements

I have a program flow as follows:我有一个程序流程如下:

if(a)
{
    if((a > b) || (a > c))
    {
        doSomething();
    }
    statementX;
    statementY;
}

I need to translate this into a conditional expression, and this is what I have done:我需要将其转换为条件表达式,这就是我所做的:

(a) ? (((a > b) || (a > c)) ? doSomething() : something_else) : something_else;

Where do I insert statements statementX, statementY?在哪里插入语句 statementX、statementY? As it is required to execute in both the possible cases, I cannot really find out a way.由于在这两种可能的情况下都需要执行,我真的找不到办法。

You can use comma , operator like this:您可以像这样使用逗号,运算符:

a ? (
    (a > b || a > c ? do_something : do_something_else), 
    statementX, 
    statementY
  ) 
  : something_else;

The following program:以下程序:

#include <stdio.h>

int main ()
{
    int a, b, c;

    a = 1, b = 0, c = 0;

    a ? (
      (a > b || a > c ? printf ("foo\n") : printf ("bar\n")),
      printf ("x\n"),
      printf ("y\n")
    )
    : printf ("foobar\n");
}

print for me:为我打印:

foo
x
y

Considering you're executing statements and not assigning, i'd stick with the if() condition.考虑到您正在执行语句而不是分配,我会坚持使用if()条件。 It's also arguably more readable for anyone else who may come across that piece of code.对于可能遇到那段代码的任何其他人来说,它也可以说更具可读性。

making something a one-line may appear nice, but in terms of losing readability it's not worth it (there's no performance increase).将一些东西变成一行可能看起来不错,但就失去可读性而言,这是不值得的(没有性能提升)。

You can use nested Ternary operator statements您可以使用嵌套的三元运算符语句

if(a)
{
if((a > b) || (a > c))
{
    printf("\nDo something\n");
}
printf("\nstatement X goes here\n");
printf("\nstatement X goes here\n");
}

The above code , can be replaced by上面的代码,可以替换为

(a) ? (   ( a>b || a>c )? printf("\nDo something\n");  :  printf("\nstatement X goes here\n");printf("\nstatement Y goes here\n");  )   : exit (0);

The Obvious Advantage here is to be able to reduce the number of code lines for a given logic , but at the same time decreases code readability as well.这里的明显优势是能够减少给定逻辑的代码行数,但同时也降低了代码的可读性。

The C ternary operator precedence and association is design to allow for this: C 三元运算符优先级和关联的设计允许这样做:

return c1 ? v1 :
       c2 ? v2 :
       c3 ? v3 :
       c4 ? v4 :
       vdefault;

As == != >= <= < >, &&, ||, ^^ operators have higher precedence than the ternary, parenthesis aren't required due to the ternary operator itself.由于 == != >= <= < >, &&, ||, ^^ 运算符的优先级高于三元运算符,因此由于三元运算符本身,不需要括号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM