For example, there is a code in C:

if (a > 0) { if (b > 0) c = a; } else c = b; 

Is it possible to write this with a ternary operator?

In this case, I tried to go from the false branch mostly if, but it turns out that for the ternary there is not enough condition after the ":". How to be?

    2 answers 2

     c = a > 0 && b > 0 ? a : b; 
    • 3
      When a> 0, & b <0 does c = b, which is wrong. Answer c = a> 0? b> 0? a: c: b; - alexlz
    • yes, strictly speaking, either @alexlz is right or the vehicle is wrong: the condition needs another else c = b so that the answer is correct - mega
     c = (a > 0) ? (b > 0) ? a : c : b ; 

    Verbatim.