205

I'm personally an advocate of the ternary operator: () ? :

I do realize that it has its place, but I have come across many programmers that are completely against ever using it, and some that use it too often.

What are your feelings on it? What interesting code have you seen using it?

4
  • 9
    Use it when it's clear, avoid it when it confuses. That's a judgment call. It can make code more readable, but only for simple expressions. Trying to always use it is just as much a menace as relentlessly avoiding it.
    – Abel
    Nov 5, 2009 at 4:40
  • 4
    Actually, it's the conditional operator. A close-to-duplicate question is stackoverflow.com/questions/725973/…. Oct 28, 2011 at 22:22
  • I was sometimes using x = x if x else y but then asked about it and realized with others help that it really just reduces to x = x or y (stackoverflow.com/questions/18199381/self-referencing-ternary/…)
    – Scruffy
    Aug 14, 2013 at 13:45
  • The ternary operator can be used in places where the if..else construct can't, for example in return statements, and as function arguments. The same could be achieved without ternary use, but results in longer code and larger executables. Mar 1, 2016 at 3:02

54 Answers 54

1
2
2

Use it to:

  • access object (array) properties:

    var status = statuses[error == null ? 'working' : 'stopped'];
    
  • return statements:

    function getFullName(){
        return this.isMale() ? "Mr. " : "Ms. " + this.name;
    }
    
  • initialize variables:

    var formMethod = DEBUG_FLAG == true ? "GET" : "POST";
    
  • validate arguments:

    function(object){
        var prop1 = typeof object.property == 'undefined'
                  ? "default prop"
                  : object.property;
        //...
    }
    

Code examples are in JavaScript.

1

My recently formulated rule of thumb for determining whether you should use the ternary operator is:

  • if your code is choosing between two different values, go ahead and use the ternary operator.
  • if your code choosing between two different code paths, stick to an if statement.

And be kind to readers of your code. If you are nesting ternary operators, format the code to make that nesting obvious.

1

No. They are hard to read. If/Else is much easier to read.

This is my opinion. Your mileage may vary.

1

The ternary operator hands down. They aren't complex if you format properly. Take the leap year example from paxdiablo:

$isLeapYear =
   (($year % 400) == 0)
   ? 1
   : ((($year % 100) == 0)
      ? 0
      : ((($year % 4) == 0)
         ? 1
         : 0));

This can be written more concise and be made much more readable with this formatting:

//--------------Test expression-----Result
$isLeapYear = (($year % 400) == 0) ? 1 :
              ((($year % 100) == 0)? 0 :
              ((($year % 4) == 0)  ? 1 :
                                     0)); // Default result
1

I would say that the number of conditions in a logic expression make it harder to read. This is true of an if statement and this is true of a ternary operator. In a perfect world, there should be one summarizable reason for taking a branch as opposed to others. Chances are that it really is more of a "business rule" if your explanation is "only when this cluster of states occur".

However, in the real world, we don't add intermediate steps to fold states into one expressible state simply to obey the ideal case. We have made inferences about multiple states and have to make a decision on how to handle them.

I like ternaries because it's possible to do anything with an if statement.

if( object.testSomeCondition()) {
    System.exec( "format c:" );
}
else {
    a++;
}

On the other hand:

a += ( object.testSomeCondition() ? 0 : 1 );

makes it clear that the goal is to find a value for a. Of course, in line with that, there probably shouldn't be more than reasonable side effects.

  • I use an if for long or complex conditions after I've decided whether I have the time to rework conditions upstream so that I'm answering an easier question. But when I use an if, I still try to do parallel processing, just under a different condition.

      if (  user.hasRepeatedlyPressedOKWithoutAnswer()
         && me.gettingTowardMyLunchtime( time )
         ) {
          ...
      }
    
  • Also my goal is near-single-stream processing. So I often try not to do an else and an if is simply a step off the common path. When you do a lot of single-stream processing, it's much harder for bugs to hide in your code waiting for that one condition that will jump out and break things.

  • As I said above, if you use a ternary to set one thing, or you have a small number of cases you want to test in order to set it to a value, then I just like the readability of a ternary.

  • With one caveat--> NO COMPLEX true CLAUSES

      a = b == c ? ( c == d ? ( c == e ? f : g ) : h ) : i;
    

Of course that can be decomposed into:

a = b != c ? i
  : c != d ? h
  : c == e ? f
  :          g
  ;

And it looks like a (compressed) truth table.

Remember that there are more important factors for readability. One of them is block length and another is indentation level. Doing simple things in ternaries doesn't create an impetus to further and further levels of indentation.

0

I use and recommend ternaries to avoid code lines in situations where the logic is trivial.

int i;
if( piVal ) {
    i = *piVal;
} else {
    i = *piDefVal;
}

In the above case I would choose a ternary, because it has less noise:

int i = ( piVal ) ? *piVal : *piDefVal;

Likewise conditional return values are good candidates:

return ( piVal ) ? *piVal : *piDefVal;

I think compactness can improve readability which in turn helps to improve the code quality.

But readability always depends on the code's audience.

The readers must be able to understand the a ? b : c pattern without any mental effort. If you can not presume this, go for the long version.

1
  • I agree. Once you understand how they work, it is way more readable. Ternary operators are the greatest thing since the foreach loop!
    – Anonymous
    Oct 2, 2008 at 14:08
0

No, ternary operators do not increase complexity. Unfortunately, some developers are so oriented to an imperative programming style that they reject (or won't learn) anything else. I do not believe that, for example:

int c = a < b ? a : b;

is "more complex" than the equivalent (but more verbose):

int c;
if (a < b) {
    c = a;
} else {
    c = b;
}

or the even more awkward (which I've seen):

int c = a;
if (!a < b) {
    c = b;
}

That said, look carefully at your alternatives on a case-by-case basis. Assuming a propoerly-educated developer, ask which most succinctly expresses the intent of your code and go with that one.

4
  • 1
    int c = MIN( a, b ); // Seems clearer than the ternary operator. Feb 11, 2009 at 1:52
  • And MIN is defined where in the C standard? You still have to write code to implement it, as in: int MIN (int n1, int n2) { return (n1 < n2) ? n1 : n2; }".
    – paxdiablo
    Feb 11, 2009 at 2:09
  • @causualcode: It was an example.
    – joel.neely
    Feb 11, 2009 at 12:33
  • how about: int c = b; if (a < b) c = a;?
    – obe
    Aug 9, 2018 at 14:06
0

I used to be in the “ternary operators make a line un-readable” camp, but in the last few years I’ve grown to like them when used in moderation. Single line ternary operators can increase readability if everybody on your team understands what’s going on. It’s a concise way of doing something without the overhead of lots of curly braces for the sake of curly braces.

The two cases where I don’t like them: if they go too far beyond the 120 column mark or if they are embedded in other ternary operators. If you can’t quickly, easily and readably express what you’re doing in a ternary operator. Then use the if/else equivalent.

0

No (unless they're misused). Where the expression is part of a larger expression, the use of a ternary operator is often much clearer.

0

I think it really depends on the context they are used in.

Something like this would be a really confusing, albeit effective, way to use them:

 __CRT_INLINE int __cdecl getchar (void)
{
   return (--stdin->_cnt >= 0)
          ?  (int) (unsigned char) *stdin->_ptr++
          : _filbuf (stdin);
}

However, this:

c = a > b ? a : b;

is perfectly reasonable.

I personally think they should be used when they cut down on overly verbose IF statements. The problem is people are either petrified of them, or like them so much they get used almost exclusively instead of IF statements.

0

string someSay = bCanReadThis ? "No" : "Yes";

0

I agree with the sentiments of many of the posters here. The ternary operator is perfectly valid as long as it is used correctly and does not introduce ambiguity (to be fair, you can say that about any operator/construct).

I use the ternary operator often in embedded code to clarify what my code is doing. Take the following (oversimplified for clarity) code samples:

Snippet 1:

int direction = read_or_write(io_command);

// Send an I/O
io_command.size = (direction==WRITE) ? (32 * 1024) : (128 * 1024);
io_command.data = &buffer;
dispatch_request(io_command);

Snippet 2:

int direction = read_or_write(io_command);

// Send an I/O
if (direction == WRITE) {
    io_command.size = (32 * 1024);
    io_command.data = &buffer;
    dispatch_request(io_command);
} else {
    io_command.size = (128 * 1024);
    io_command.data = &buffer;
    dispatch_request(io_command);
}

Here, I am dispatching an input or output request. The process is the same whether the request is a read or a write, only the default I/O size changes. In the first sample, I use the ternary operator to make it clear that the procedure is the same and that the size field gets a different value depending on the I/O direction. In the second example, it is not as immediately clear that the algorithm for the two cases is the same (especially as the code grows much longer than three lines). The second example would be more difficult to keep the common code in sync. Here, the ternary operator does a better job of expressing the largely parallel nature of the code.

The ternary operator has another advantage (albeit one that is normally only an issue with embedded software). Some compilers can only perform certain optimizations if the code is not "nested" past a certain depth (meaning inside a function, you increase the nesting depth by 1 every time you enter an if, loop, or switch statement and decrease it by 1 when you leave it). On occasion, using the ternary operator can minimize the amount of code that needs to be inside a conditional (sometimes to the point where the compiler can optimize away the conditional) and can reduce the nesting depth of your code. In some instances, I was able to re-structure some logic using the ternary operator (as in my example above) and reduce the nested depth of the function enough that the compiler could perform additional optimization steps on it. Admittedly this is a rather narrow use case, but I figured it was worth mentioning anyway.

2
  • 1
    Why don't you move io_command.data = &buffer; and dispatch_request(io_command); outside of the if-else statement though? Just place them afterward. Less code duplication. May 3, 2010 at 1:09
  • This is not fair. The last two statements do not depend on the condition. And should thus not be in the 'if' statement. Oct 27, 2020 at 18:59
0

Interesting anecdote: I have seen the optimizer weigh the ternary operator as less "heavy" for the purposes of inlining than the equivalent if. I noticed this with Microsoft compilers, but it could be more widespread.

In particular functions like this would inline:

int getSomething()
{
    return m_t ? m_t->v : 0;
}

But this wouldn't:

int getSomething()
{
    if( m_t )
        return m_t->v;
    return 0;
}
0

I like it a lot. When I use it, I write it like an if-then-else: one line each for condition, true action, and false action. That way, I can nest them easily.

Example:

x = (a == b
     ? (sqrt(a) - 2)
     : (a*a + b*b)
     );

x = (a == b
     ? (sqrt(a) - 2)
     : (a*a + b*b)
     );
x = (a == b
     ? (c > d
        ? (sqrt(a) - 2)
        : (c + cos(d))
       )
     : (a*a + b*b)
     );

To me, this is reasonably easy to read. It also makes it easy to add subcases or change existing cases.

3
  • 1
    I thought I was a huge fan until I saw that example. That would take some getting used to. I use them for one-liners, not blocks. Oct 2, 2008 at 3:33
  • 2
    Just go buy yourself a Lisp, you closeted homoschemual.
    – niXar
    Jan 7, 2009 at 23:14
  • This looks horrible. And I consider myself a fan of the operator. May 2, 2010 at 23:47
0

If your ternary operator ends up taking the whole screen width, then I wouldn't use it. I keep it to just checking one simple condition and returning single values:

int x = something == somethingElse ? 0 : -1;

We actually have some nasty code like this in production...not good:

int x = something == (someValue == someOtherVal ? string.Empty : "Blah blah") ? (a == b ? 1 : 2 ): (c == d ? 3 : 4);
1
  • There is actually a language where writing string.Empty makes any sense? What happened to ""?
    – niXar
    Jan 7, 2009 at 23:17
0

The ternary operator is extremely useful for concisely producing comma separated lists. Here is a Java example:

    int[] iArr = {1, 2, 3};
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < iArr.length; i++) {
        sb.append(i == 0 ? iArr[i] : ", " + iArr[i]);
    }
    System.out.println(sb.toString());

It produces: "1, 2, 3"

Otherwise, special casing for the last comma becomes annoying.

0

If you are trying to reduce the amount of lines in your code or are refactoring code, then go for it.

If you care about the next programmer that has to take that extra 0.1 millisecond to understand the expression, then go for it anyway.

0

It depends :)

They are useful when dealing with possibly null references (BTW: Java really needs a way to easily compare two possibly null strings).

The problem begins, when you are nesting many ternary operators in one expression.

2
  • Actually I disagree with your 'BTW'. Does a NULL string equal another NULL string or not? My opinion is they're not actually strings until they're non-NULL.
    – paxdiablo
    Feb 11, 2009 at 1:51
  • Maybe I'm a little biased - recently I do mostly eclipse rcp, and I can't count places in code where I've seen variations on this theme: if ( (evt.getNewValue()!=null && evt.getNewValue().equals(evt.getOldValue())) || evt.getNewValue()==evt.getOldValue()) { return; } //do sth
    – ajuc
    Feb 11, 2009 at 2:03
0

In small doses they can reduce the number of lines and make code more readable; particularly if the outcome is something like setting a char string to "Yes" or "No" based on the result of a calculation.

Example:

char* c = NULL;
if(x) {
  c = "true";
}else {
  c = "false";
}

compared with:

char* c = x ? "Yes" : "No";

The only bug that can occur in simple tests like that is assigning an incorrect value, but since the conditional is usually simple it's less likely the programmer will get it wrong. Having your program print the wrong output isn't the end of the world, and should be caught in all of code review, bench testing and production testing phases.

I'll counter my own argument with now it's more difficult to use code coverage metrics to assist in knowing how good your test cases are. In the first example you can test for coverage on both the assignment lines; if one is not covered then your tests are not exercising all possible code flows.

In the second example the line will show as being executed regardless of the value of X, so you can't be certain you've tested the alternate path (YMMV depending on the ability of your coverage tools).

This matters more with the increasing complexity of the tests.

1
  • Related to code coverage is the ability to set breakpoints (e.g., a seldom match could be the interesting one during debugging or other analysis). Conditional breakpoints are not always practical or possible. Oct 27, 2020 at 18:46
0

One reason no one seems to mention for using the ternary operator, at least in languages, like D, that support type inference is to allow type inference to work for amazingly complicated template types.

auto myVariable = fun();
// typeof(myVariable) == Foo!(Bar, Baz, Waldo!(Stuff, OtherStuff)).

// Now I want to declare a variable and assign a value depending on some
// conditional to it.
auto myOtherVariable = (someCondition) ? fun() : gun();

// If I didn't use the ternary I'd have to do:
Foo!(Bar, Baz, Waldo!(Stuff, OtherStuff)) myLastVariable;  // Ugly.
if(someCondition) {
    myLastVariable = fun();
} else {
    myLastVariable = gun():
}
0

I like the operator in some situations, but I think some people tend to overuse it and that it can make the code harder to read.

I recently stumbled across this line in some open source code I am working to modify.

Where

    (active == null ? true :
    ((bool)active ? p.active : !p.active)) &&...

Instead of

where ( active == null || p.active == active) &&...

I wonder if the ternary use adds extra overhead to the LINQ statement in this case.

0

Making code smaller doesn't always mean it's easier to parse. It differs from language to language.

In PHP for example, whitespace and line-breaks are encouraged since PHP's lexer first breaks the code up in bits starting with line-breaks and then whitespace. So I do not see a performance issue, unless less whitespace is used.

Bad:

($var)?1:0;

Good:

($var) ? 1 : 0;

It doesn't seem like a big issue, but with lexing code in PHP, whitespace is essential. Plus, it also reads a bit better this way.

1
  • Do you have a source for these claims? E.g. "PHP's lexer first breaks the code up in bits starting with line-breaks and then whitespace". Doesn't PHP have a true parser? What is the actual performance impact of different kind of formatting of PHP code? Oct 27, 2020 at 19:09
-1

How would anyone win an obfuscated code contest without the ternary operator?!

I'm personally for using it, when appropriate, but I don't think I'd ever nest it. It's very useful, but it has a couple knocks against it in that it makes code harder to read and is in use in some other languages in other operations (like Groovy's null-check).

-2

I'm a big fan of it ... when appropriate.

Stuff like this is great, and, personally, I don't find it too hard to read/understand:

$y = ($x == "a" ? "apple"
   : ($x == "b" ? "banana"
   : ($x == "c" ? "carrot"
   : "default")));

I know that probably makes a lot of people cringe, though.

One thing to keep in mind when using it in PHP is how it works with a function that returns a reference.

class Foo {
    var $bar;

    function Foo() {
        $this->bar = "original value";
    }

    function &tern() {
        return true ? $this->bar : false;
    }

    function &notTern() {
        if (true) return $this->bar;
        else      return false;
    }
}

$f = new Foo();
$b =& $f->notTern();
$b = "changed";
echo $f->bar;  // "changed"

$f2 = new Foo();
$b2 =& $f->tern();
$b2 = "changed";
echo $f2->bar;  // "original value"
2
  • That's because ternary operator evaluates the result and returns $this -> bar by its value whereas the other one just plain returns the variable. Oct 2, 2008 at 0:17
  • it's strange how that doesn't cause an error, since you're therefore not returning a reference.
    – nickf
    Oct 2, 2008 at 2:01
1
2

Not the answer you're looking for? Browse other questions tagged or ask your own question.