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;
} else if (x==z)
{
z += y;
} else {
z += 1;
}
i can do this now if there is only one if statement like this:
z = x == y ? z += x : z += 1;
It would be like this:
If you use
z += xas an operand it will end up doingz = (z += x). While it works in this special case, as the result of the expressionz += xis the final value ofz, it may not work in other cases.Howver, as all operations have the
z +=in common, you can do like this: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
ifstatement.