How do I use the conditional operator?

后端 未结 9 1036
忘了有多久
忘了有多久 2020-11-22 16:27

I\'ve always wondered how to write the \"A ? B : C\" syntax in a C++ compatible language.

I think it works something like: (Pseudo

9条回答
  •  难免孤独
    2020-11-22 17:05

    This is called a "Ternary operator", and the ? and : are another way of writing an if-else statement.

    Look at the "Example #1" in this Codepen, and un-comment it... you'll notice what it does.

    Now comment "Example #1", un-comment "Example #2", and see what happens. The code does the exact same thing... but this time with only 5 lines of code. Notice how whatever appears before the ? sign is the if (conditional), and whatever comes AFTER the : is the thing to be executed.

    But what if you have a conditional that requires an "else-if" (with more than 2 possible outcomes) like the one in the Codepen's "Example #3" (which adds the possibility of the user writing a specific wrong answer)? Then the ternary operator might not be as useful, but you can certainly concatenate several conditions with the ternary operator, like on this ES6 fizzbuzz example.

提交回复
热议问题