The conditional operator

Location
  1. Courses

    /

  2. Complete C++ Course

    /

  3. The basics

    /

  4. The conditional operator

That operator is also called the ternary operator. The conditional operator is used to execute an instruction if the left operand is true or an other if it is false. To code it, we must write the condition followed by the interrogation symbol ?, then the instruction to execute if the condition is true and the instruction to execute if it is false, separated by a colon :.

It can be used to retrieve a different value depending on the result of a logical operation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream> int main() { std::string name="Jacob"; // "True" is printed to the console. std::cout << ((name == "Jacob") ? "True" : "False") << std::endl; name = "Apple"; // "Red" is printed to the console. std::cout << ((name == "Banana") ? "Yellow" : "Red") << std::endl; }

In the example above, the parentheses () between the conditional operations are required, otherwise, the compiler would not know if << std::endl; is part of the conditional operations or not.

It can also be used to execute a different instruction depending on the result of a logical operation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream> int main() { std::string word="House"; (word == "Sky") ? std::cout << "The word is \"Sky\"." << std::endl : std::cout << "The word is not \"Sky\"." << std::endl; // "The word is not "Sky"." is written in the console. return 0; }