Ternary operator with multiple operators

I have a program stream 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 did:

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

Where can I insert statements statementX, statementY? Since this must be done in both possible cases, I cannot find a way.

+4
source share
3 answers

You can use the comma operator as follows:

 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"); } 

type for me:

 foo x y 
+12
source

Given that you are following instructions and not assigning, I adhere to the if() condition. It is also possibly more readable to anyone who might encounter this piece of code.

to do something single-line may seem nice, but from the point of view of loss of readability, it is not worth it (there is no increase in productivity).

+3
source

You can use the nested statements of the Ternary operator

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

The code above 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 is to reduce the number of lines of code for a given logic, but at the same time reduces the readability of the code.

+3
source

All Articles