Remembering the Ternary Operator Syntax

mnemonicsternary-operator

Anyone have a good trick to remember the standard ternary syntax?

Specifically whether the '?' or ':' comes first. I have consistently gotten this backwards over the years.

Best Answer

The condition you are checking is kind of like a question, so the question mark comes first.

x > 0 ? 1 : 0

Think of this statement as three English sentences: "Is x greater than 0? Then 1. Else, 0." You have one sentence for each clause in the statement.

The predicate:

x > 0 ? /* Is x greater than 0? */

The "true" branch:

1 /* Then 1. */

The "false" branch:

: 0 /* Else, 0. */