Ternary operator

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;

Example: ternary operator

Code Explanation

5Initializes the variable age of type integer with the value 15
6Creates a new variable message of type string
8If age is higher than 18 the string behind the question mark will be displayed. In this case “you can drive”. Otherwise, the string after the double dot is output “you are not allowed to drive a car”
10Outputs the content of the variable message
#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