+ 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?

14th Oct 2017, 7:20 PM
Adam
Adam - avatar
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.
14th Oct 2017, 7:31 PM
John Wells
John Wells - avatar
+ 5
@John It's not the case for C though it's a little bit weird to use conditional without assignment. šŸ˜‰
15th Oct 2017, 1:00 AM
Zephyr Koo
Zephyr Koo - avatar
+ 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.
14th Oct 2017, 7:27 PM
Max Ement
Max Ement - avatar