In C++, the ternary operator is used to replace a multiline if-else
code with a single line. It’s a shorthand if-else
statement as it contains three operands.
variable = (condition) ? expressionTrue : expressionFalse;
In the code above, the expressionTrue
represents a block of code or statement to be executed if the condition
given is true
. The expressionFalse
will execute if the given condition
is false
.
Next, let’s illustrate the practicality of the ternary operator using a few code examples.
if-else
statement#include <iostream>using namespace std;int main() {if (1 > 2) {cout << "1 is greater than 2";} else {cout << "1 is less than 2";}return 0;}
if
to write a condition—if 1
is greater than 2
, the code executes the "1 is greater than 2"
statement.else
to execute another statement if the condition is false
.We use multiple lines of codes in writing the program above. To avoid such situations, we use the ternary operator.
#include <iostream>#include <string>using namespace std;int main() {int a = 1;string result = (a > 2) ? "1 is greater than 2" : "1 is less than 2";cout << result;return 0;}
a
.a
is greater than 2
, the code executes the expressionTrue
statement. Otherwise, it executes the expressionFalse
statement.As shown in the code above, the ternary operator reduces multiple lines of code to a single line of code.