To ternary or not to ternary? [closed]

Use it for simple expressions only:

int a = (b > 10) ? c : d;

Don't chain or nest ternary operators as it hard to read and confusing:

int a = b > 10 ? c < 20 ? 50 : 80 : e == 2 ? 4 : 8;

Moreover, when using ternary operator, consider formatting the code in a way that improve readability:

int a = (b > 10) ? some_value                 
                 : another_value;

It makes debugging slightly more difficult since you can not place breakpoints on each of the sub expressions. I use it rarely.


I love them, especially in type-safe languages.

I don't see how this:

int count = (condition) ? 1 : 0;

is any harder than this:

int count;

if (condition)
{
  count = 1;
}
else
{
  count = 0;
}

I'd argue that ternary operators make everything less complex and more neat than the alternative.


Chained I'm fine with - nested, not so much.

I tend to use them more in C simply because they're an if statement that has value, so it cuts down on unnecessary repetition or variables:

x = (y < 100) ? "dog" :
    (y < 150) ? "cat" :
    (y < 300) ? "bar" : "baz";

rather than

     if (y < 100) { x = "dog"; }
else if (y < 150) { x = "cat"; }
else if (y < 300) { x = "bar"; }
else              { x = "baz"; }

In assignments like this, I find it's less to refactor, and clearer.

When I'm working in ruby on the other hand, I'm more likely to use if...else...end because it's an expression too.

x =   if (y < 100) then "dog"
    elif (y < 150) then "cat"
    elif (y < 300) then "bar"
    else                "baz"
    end

(Although, admittedly, for something this simple, I might just use the ternary operator anyway.)