C语言 具有多个语句的三元运算符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15113897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ternary operator with multiple statements
提问by user2053912
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? As it is required to execute in both the possible cases, I cannot really find out a way.
在哪里插入语句 statementX、statementY?由于在这两种可能的情况下都需要执行,我真的找不到办法。
回答by Mikhail Vladimirov
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
回答by Brad Christie
Considering you're executing statements and not assigning, i'd stick with the if()condition. It's also arguably more readable for anyone else who may come across that piece of code.
考虑到您正在执行语句而不是分配,我会坚持使用if()条件。对于可能遇到那段代码的任何其他人来说,它也可以说更具可读性。
making something a one-line may appear nice, but in terms of losing readability it's not worth it (there's no performance increase).
将一些东西变成一行可能看起来不错,但就失去可读性而言,这是不值得的(没有性能提升)。
回答by Barath Ravikumar
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.
这里的明显优势是能够减少给定逻辑的代码行数,但同时也降低了代码的可读性。

