Example of Ternary Operator in C++
C++
// C++ program to illustrate the use of ternary operator #include <iostream> using namespace std; int main() { // creating a variable int num, test = 40; // assigning the value of num based on the value of test // variable num = test < 10 ? 10 : test + 10; printf ( "Num - Test = %d" , num - test); return 0; } |
Num - Test = 10
In the above code, we have used the ternary operator to assign the value of the variable num depending upon the value of another variable named test.
Note: The ternary operator have third most lowest precedence, so we need to use the expressions such that we can avoid errors due to improper operator precedence management.
C++ Ternary or Conditional Operator
In C++, the ternary or conditional operator ( ? : ) is the shortest form of writing conditional statements. It can be used as an inline conditional statement in place of if-else to execute some conditional code.