A simple if statement can also be written as a conditional expression.
The following is a simple if-statement:
#include <iostream> int main() /*from w ww .ja v a2 s. c om*/ { bool mycondition = true; int x = 0; if (mycondition) { x = 1; } else { x = 0; } std::cout << "The value of x is: " << x << '\n'; }
To rewrite the previous example using a conditional expression, we write:
#include <iostream> int main() /* w w w . j a v a2 s . c o m*/ { bool mycondition = true; int x = 0; x = (mycondition) ? 1 : 0; std::cout << "The value of x is: " << x << '\n'; }
The conditional expression is of the following syntax:
(condition) ? expression_1 : expression_2
The conditional expression uses the unary ? operator, which checks the value of the condition.
If the condition is true, it returns expression_1.
If the condition is false, it returns expression_2.
It can be thought of as a way of replacing a simple if-else-statement with an one liner.