Search code examples
cif-statementternary-operator

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.


Solution

  • 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