The conditional (ternary) operator is often used as a short form of an if-else statement. This is simply a conditional assignment of a value to a variable. if-then-else, on the other hand, is a flow control.
condition ? expression1 : expression2;
This code defines an integer variable age
with a value of 15, and a string variable message
. It then uses the ternary operator to set the value of message
based on whether age
is greater than 18.
The ternary operator condition ? value_if_true : value_if_false
works by evaluating the condition before the ?
. If the condition is true, it returns the value after the ?
, otherwise it returns the value after the :
. In this case, if age
is greater than 18, the condition is true, so message
is set to "you can drive"
. If age
is not greater than 18, the condition is false, so message
is set to "you are not allowed to drive a car"
.
#include <iostream>
using namespace std;
int main() {
int age = 15;
string message;
message = age > 18 ? "you can drive" : "you are not allowed to drive a car";
cout << message;
return 0;
}
you are not allowed to drive a car