?:
In case the statement associated with
if and the statement
associated with
else are both expressions,
an alternative more concise form can be used:
int a;
cin >> a;
a > 3 ? 10 : 20;
The statement above means “if a is greater than 3 the overall expression
evaluates to 10, otherwise it evaluates to 20”.
As the statement evaluates to one of two expressions (in the case above,
simply 10 or 20) it can be assigned to an lvalue of a proper type.
Example
#include <iostream>
#include <cmath>// necessary to use the function pow, which calculates a power
using namespace std;
int main()
{
cout << "Enter a value, please ";
int a;
cin >> a;
int x = a > 3 ? 10 : 20;
cout << "x\'s value is " << x << endl;
double y = a > 3 ? pow(10, 2) : pow(20, 2);
cout << "y\'s value is " << y << endl;
}
Output
Enter a value, please 4
x's value is 10
y's value is 100