Book: Starting Out with C++ from Control Structures to Objects, byTony Gaddis, ninth edition
You can use the conditional operator to create short expressions that work like if/else statements.
There is also a short-hand if else, which is known as the ternary operator because it consists of three operands. It can be used to replace multiple lines of code with a single line. It is often used to replace simple if else statements:
Format:
expression1 ? expression2 : expression3;
Example01:
x < 0 ? y = 10 : z = 20;
1st Expression: Expression to be tested.
2nd Expression: Excutes if the 1st expression is true.
3rd Expression: Excutes if the 1st expression is false.
// This program calculates a consultant's charges at $50
// per hour, for a minimum of 5 hours. The `? :` (conditional) operator
// adjusts hours to 5 if less than 5 hours were worked.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
const double PAY_RATE = 50.0; // Hourly pay rate
const int MIN_HOURS = 5; // Minimum billable hours
double hours, // Hours worked
charges; // Total charges
cout << "How many hours were worked? ";
cin >> hours;
// Use Ternary Operator to determine the hours to charge for.
hours = hours < MIN_HOURS ? MIN_HOURS : hours;
charges = PAY_RATE * hours;
cout << fixed << showpoint << setprecision(2)
<< "The charges are $" << charges << endl;
return 0;
}
How many hours were worked? 2
The charges are $250.00
How many hours were worked? 8
The charges are $400.00
Reference:
Book: Starting Out with C++ from Control Structures to Objects, byTony Gaddis, ninth edition
There is also a short-hand if else, which is known as the ternary operator because it consists of three operands. It can be used to replace multiple lines of code with a single line. It is often used to replace simple if else statements:
Format:
Example01:
Same as:
Example02:
Syntax:
Example03:
Example04:
Demonstration: