Remembering the Ternary Operator Syntax

后端 未结 7 1760
误落风尘
误落风尘 2021-01-05 08:11

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

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

相关标签:
7条回答
  • 2021-01-05 08:40

    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. */
    
    0 讨论(0)
提交回复
热议问题