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

后端 未结 6 1920
执念已碎
执念已碎 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 20:53

    It would be like this:

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

    If you use z += x as an operand it will end up doing z = (z += x). While it works in this special case, as the result of the expression z += x is the final value of z, it may not work in other cases.

    Howver, as all operations have the z += in common, you can do like this:

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

    Use with care, though. The code is often more readable and maintainable the simpler it is, and nested conditional operations are not very readable. Also, use this only when you have an expression as the result of the conditional operation, it's not a drop-in replacement for the if statement.

提交回复
热议问题