Use it when you're selecting between two simple values, especially as an initializer, return value, or function argument, int y = (x >= 0) ? x : -x; is a clearer absolute-value than three lines of if/else. Avoid it when the two branches have side effects (function calls that do work) rather than just yielding values, when the condition is complex, or when you find yourself nesting ternaries, a ? b : c ? d : e is unreadable and should be split into named variables or an if/else chain. Ternaries are a refinement tool, not a way to look clever.
Programming Fundamentals · Interview question
When should you reach for the ternary ? : operator, and when should you avoid it?
A strong answer
What a weak answer sounds like
You know the answer. Do you know what gets you dinged?
Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.
From the lesson
Conditionals
How a program makes decisions. if, else if, and else, with the dangling-else trap and the ternary shortcut for one-line choices.