+ 4
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?
3 Answers
+ 3
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.
+ 5
@John It's not the case for C though it's a little bit weird to use conditional without assignment. š
+ 3
Nope, no difference in your simple case. Only readability and expansion perspectives. Use ternary for 'one-line' operations, for example in return statement logic.