If-else statement vs ternary operator | Sololearn: Learn to code for FREE!


If-else statement vs ternary operator

What is the difference between using an if-else statement or the ternary operator? They both say that if a is true then execute b if not execute c. Are there different use cases? To me it seems that if I just need to write a simple if-else statement, the ternary operator is much shorter to write. Other than length is there a difference?

10/14/2017 7:20:51 PM

🐧 Eitan Prezes

3 Answers

New Answer


The ternary operator can't be used to call a void function or a list of statements. It must be used to assign/return a value.


@John It's not the case for C though it's a little bit weird to use conditional without assignment. 😉


Nope, no difference in your simple case. Only readability and expansion perspectives. Use ternary for 'one-line' operations, for example in return statement logic.