Benefits of using the conditional ?: (ternary) operator

KChaloux picture KChaloux · Jul 22, 2010 · Viewed 160k times · Source

What are the benefits and drawbacks of the ?: operator as opposed to the standard if-else statement. The obvious ones being:

Conditional ?: Operator

  • Shorter and more concise when dealing with direct value comparisons and assignments
  • Doesn't seem to be as flexible as the if/else construct

Standard If/Else

  • Can be applied to more situations (such as function calls)
  • Often are unnecessarily long

Readability seems to vary for each depending on the statement. For a little while after first being exposed to the ?: operator, it took me some time to digest exactly how it worked. Would you recommend using it wherever possible, or sticking to if/else given that I work with many non-programmers?

Answer

Dan Tao picture Dan Tao · Jul 22, 2010

I would basically recommend using it only when the resulting statement is extremely short and represents a significant increase in conciseness over the if/else equivalent without sacrificing readability.

Good example:

int result = Check() ? 1 : 0;

Bad example:

int result = FirstCheck() ? 1 : SecondCheck() ? 1 : ThirdCheck() ? 1 : 0;