What is the correct form of the ternary conditional operator?

Enhance your programming skills with the RECF Programming Test. Features flashcards and multiple choice questions with hints and explanations. Prepare for success!

Multiple Choice

What is the correct form of the ternary conditional operator?

Explanation:
The ternary conditional operator is a concise way to pick between two expressions based on a condition. Its form is: condition ? exprIfTrue : exprIfFalse. After the condition is evaluated, if it’s true the first expression is used; otherwise the second expression is used. This lets you produce a value in a single expression, for example: int z = (x > y) ? x : y;. The other forms don’t fit because they don’t follow this expression-based pattern. The first option is an if-else block with braces, which performs statements rather than returning a value in a single expression. The third option uses a null-coalescing operator (often written with two question marks) that serves a different purpose. The fourth option misplaces the colon and question mark, making it invalid syntax for the ternary operator.

The ternary conditional operator is a concise way to pick between two expressions based on a condition. Its form is: condition ? exprIfTrue : exprIfFalse. After the condition is evaluated, if it’s true the first expression is used; otherwise the second expression is used. This lets you produce a value in a single expression, for example: int z = (x > y) ? x : y;.

The other forms don’t fit because they don’t follow this expression-based pattern. The first option is an if-else block with braces, which performs statements rather than returning a value in a single expression. The third option uses a null-coalescing operator (often written with two question marks) that serves a different purpose. The fourth option misplaces the colon and question mark, making it invalid syntax for the ternary operator.

Subscribe

Get the latest from Passetra

You can unsubscribe at any time. Read our privacy policy