Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? As it is required to execute in both the possible cases, I cannot really find out a way.

like image 866
user2053912 Avatar asked Feb 27 '13 13:02

user2053912


People also ask

Can we use multiple statements in ternary operator?

Yes, we can, but with one proviso… There is no block demarcation so that action should be simple, else it would be better to abstract it away in a function and call the function from the ternary. Something we commonly see is console.

How do you use ternary operator for 3 conditions?

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.

Can you chain ternary operators?

A Ternary Operator in Javascript is a special operator which accepts three operands. It is also known as the "conditional" or "inline-if" operator. Ternary Operator in Javascript makes our code clean and simpler. It can be chained like an if-else if....else if-else block.

How many arguments does a ternary operator take?

The ternary operator take three arguments: The first is a comparison argument. The second is the result upon a true comparison. The third is the result upon a false comparison.


1 Answers

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
like image 67
Mikhail Vladimirov Avatar answered Nov 06 '22 19:11

Mikhail Vladimirov