Ternary operator with multiple statements

29,334

Solution 1

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

Solution 2

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.

making something a one-line may appear nice, but in terms of losing readability it's not worth it (there's no performance increase).

Solution 3

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.

Solution 4

The C ternary operator precedence and association is design to allow for this:

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.

Share:
29,334
user2053912
Author by

user2053912

Updated on December 01, 2020

Comments

  • user2053912
    user2053912 over 3 years

    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.

  • user2053912
    user2053912 over 11 years
    Simple, yet precise. Thanks.
  • thomasrutter
    thomasrutter almost 3 years
    I've seem to recall I've used languages where operator precedence rules meant that you couldn't stack ternary expressions like this without an increase number of levels of parentheses. Nice to know that C doesn't.