Using the ternary operator for multiple operations

后端 未结 5 1825
萌比男神i
萌比男神i 2020-12-30 02:44

How can I use the ternary ? : condition to perform multiple operations, if expression is true/false?

wbsource = (exp) ? (Do one thing) : (Do secon

5条回答
  •  执笔经年
    2020-12-30 03:37

    If this was c you'd be OK thanks to the "comma operator":

    int b;
    int a = (1==1) ? (b=6, somemethod(), 1) : (b=7, 2);
    

    Here b will be set to 6, somemethod will be called and then a is set to 1.

    Thankfully that was one feature that was not ported over, use if..else it's much clearer.

提交回复
热议问题