If you’re not familiar with the conditional operator (and I don’t blame you – there was no mention of it in my first programming textbook) you’re really missing out on a very useful tool, that could improve your coding skills.

What is the conditional operator

The conditional operator allows you to assign a value to a variable depending on a boolean statement.

Take this pseudocode for example:

The value of the variable b is dependent on the value of the variable a. Because of that we can use a ternary operator instead:

The paranthesis around the boolean statement (the test) are not really neccesary, but does improve readability. Whitespace is also not neccesary, you would have obtained the same result with

Although this is very handy in codegolfing (if you don’t know what that is check out my previous blog post about codegolfing), you should use proper spacing in Ternary Operators.

 

Nested conditional operator

Some programming languages allow you to nest the conditional operators like this:

While this can be okay with simple short variables, you quickly lose the grip on what you’re trying to do here, and you might as well introduce multiple if statements or a switch statement. Another simple way to made nested conditionals look readeble, is by indenting the next lines so you get

 

Which languages support the conditional operator

Almost all popular languages support the operator including very old ones like Ada and ALGOL 68. Here is a list of the most common languages that support the operator

  • AWK
  • C
  • C++
  • C#
  • Java
  • JavaScript
  • Lua
  • SQL
  • Perl
  • PHP
  • Python
  • R
  • Ruby

I thought this operator was called the ternary operator

The operator is a ternary operator – which means that it’s an operator that takes three oprands (for more information, see Wikipedia). In almost all programming languages it is the only operator that takes three operands – which explains why it is commonly called the ternary operator.

 

Example – Short tags in PHP

When injecting variable PHP code into HTML it can be annoying to do this:

With short tags and using the conditional operator you can do this instead:

 

 

Performance

Let’s look at the following C# code

The assembly generated in Visual Studio from this code

The Ternary version of this is

The assembly generated in Visual Studio from this code

There are 10 instructions (including a nop) in the first one, but only 8 in the other. After some testing the result is a 6% performance improvement (using 1.000.000 iterations).

Conclusion

The ternary operator provides us with the following:

  • Better performance
  • Easy readability (to a certain degree…)
  • Less code

 

If you’re hoping to never write and if statement again, you’re out of luck. However this is a tool that doesn’t get the glory that it truly deserved.