Ad space (banner)
Lesson 18 / 20

The Ternary Operator

This lesson covers the ternary operator, which lets you write an if statement in a single line. It's for anyone searching "C++ ternary operator usage."

The form condition ? value-if-true : value-if-false picks one of two values based on a condition, all in one line. For a simple branch, it's more compact than an if statement.

The example decides between "Pass" and "Fail" based on the value of int score = 75;, using the ternary operator.

A common early mistake is overusing the ternary operator until it becomes hard to read. It's convenient for a simple condition, but nesting them makes things confusing instead โ€” an if statement is the better choice for complex conditions.

In real projects, the ternary operator is used to keep code compact โ€” a simple conditional assignment to a variable, for example.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C++ directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)