Search code examples
cternary

C ternary : do two distinct things


I was asking myself if its was possible to do something like that :

condition ? do this && THIS : else;

like :

nb = (nb1 + nb2) > 9 ? (nb1 + nb2) % 10 && nb1 + 1 : 0;

Note this is just an example, it means nothing.


Solution

  • There is a simple way:

    condition ? function_that_does_several_things() : else_expr;
    

    The other thing is you can collect expressions in a list:

    int a = (1,2);
    

    assigns 2 to a. So you can try this:

    condition ? (do_this, and_this) : else_expr;
    

    But I suggest against it; it's really hard to see what is going on here and a lot of people will be confused, surprise and frustrated when they see such code.