How to turn if, else if logic into a ternary operator?

后端 未结 6 1907
执念已碎
执念已碎 2020-12-28 20:12

I was just wondering if this was possible because i started using ternary operators to reduce lines of code and i am loving it.

if (x==y)
{
    z += x;
} els         


        
6条回答
  •  [愿得一人]
    2020-12-28 21:00

    You can use

    z += x == y ? x : x == z ? y : 1;
    

    But honestly, that's not really more readable than what you had before. You can make it slightly clearer by adding parentheses:

    z += x == y ? x : (x == z ? y : 1);
    

    But generally I'd stay away from nested conditional operators unless when golfing.

提交回复
热议问题