Ternary operators vs if-else statements

jraleman
3 min readJan 7, 2018

You have probably seen a ternary operator (also known as a conditional expression) before in a source file, or somewhere else. In C, and in a lot of language with similar syntax, we use the ? character to represent this operator.

Most beginners (by my own experience), find it a bit difficult to understand this operator, even though they have already mastered the if and else statements. I believe the reason for this is that it is a bit difficult to read and to write it, because having different operations in the same line can be confusing. Really.

Most likely, you already know how to use them, or at least, how to read and understand the logic behind them. In case you don’t, maybe the following “beautiful” ASCII art representation that I just made for you guys, will help you out.

       yes
__ __ __ __
| |
| |
| ^
condition ? true : false
| ^
| |
|__ __ __ __ __ __ __|
no

A ternary operator takes three arguments. The first one (1st) is the condition, the second one (2nd) is executed if the condition is true, and the third one (3rd) is executed if the condition is false.

In layman’s term, it’s just an {if-else} statement in one (1) line!

When to use them?

Personally, I use them when I want to set a value to a variable, depending on a condition. For example, let’s say that if x == 42 , I want the variable y to be True . If x is not equal to 42 , then the value of the variable y is False .

So, how do I write that? Just like this…

bool y = (x == 42) ? true : false;

Easy! Try it yourself. Also, here is the Python version, just because:

y = "True" if x == 42 else "False"

How about an if-else statement?

In this case, I would argue and be against it. Why? Take a look at this code:

bool y;if (x == 42){
y = true;
}
else {
y = false;
}

To “translate” it to a ternary operator, we would do it the following way:

? -> if (x == 42) {}
y -> true;
: -> else {}
y -> false;

So we can have something like this, assuming you want it to be in one line:

bool y; if (x == 42) {y = true;} else {y = false;}

Which is ugly and unnecesary, because we can write it like this:

bool y = (x == 42) ? true : false;

See? So much cleaner! We reduced seven (7) lines of code to just one (1) line. :)

When should I avoid it?

Ternary operators are awesome, but they’re not always needed. Suppose you just want to execute a function, or do multiple operations… don’t use ternaries.

Which one would you prefer?

if (x == 42) {
std::cout << "code is executed" << std::endl;
code();
}
else {
std::cout << "nothing happened" << std::endl;
}

vs

(x == 42) ? ((std::cout << "code is executed" << std::endl), code()) : (void)(std::cout << "nothing happened" << std::endl);

Yeah, now it’s easy to see why.

Conclusion

  • Use ternary operators to set a value to a variable, or to reduce code if necessary.
  • Use if-else statements for everything else.

--

--