Ternary operator usage example:
The ternary operator as the name indicates requires three operands.
The syntax is condition ? result 1 : result 2;. Here you write the condition in front of the question mark (?) followed by result 1 and result 2 separated by a colon (:). If the condition is met, the result is 1, otherwise the result is 2.
Introduction to the ternary operator in programming languages
This operator is rare because it has three operands. But it is indeed a type of operator because it also ultimately produces a value. This is different from the ordinary if-else statement described in the later section of this chapter. The expression takes the form:
Of course, you can also use an ordinary if-else statement (described later), but the ternary operator is more concise. Although C is proud of being a concise language, and the ternary operator was probably introduced to reflect this efficient programming, if you plan to use it frequently, you still need to think more first - —It can easily produce code that is extremely unreadable.
A conditional operator can be used for its own "side effects", or for the values it produces. But you should generally use it with values, because that clearly distinguishes the operator from if-else. Here is an example: