Qingquan-Li / blog

My Blog
https://Qingquan-Li.github.io/blog/
132 stars 16 forks source link

C++ Conditional Operator (Ternary Operator) #192

Open Qingquan-Li opened 2 years ago

Qingquan-Li commented 2 years ago

Reference:

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;
  1. 1st Expression: Expression to be tested.
  2. 2nd Expression: Excutes if the 1st expression is true.
  3. 3rd Expression: Excutes if the 1st expression is false.

Same as:

if (x < 0)
    y =10;
else
    z = 20;


Example02:

Syntax:

variable = (condition) ? expressionTrue : expressionFalse;
#include <iostream>

using namespace std;

int main() {
    int age;
    bool is_senior;
    cout << "How old are you? ";
    cin >> age;
    // is_senior = age >= 65 ? true : false; // Expression can be simplified
    is_senior = age >= 65;
    cout << "Is senior? " << is_senior << endl;
    return 0;
}
How old are you? 25
Is senior? 0


Example03:

#include <iostream>

using namespace std;

int absoluteValue(int);

int main() {
    cout << absoluteValue(-100);
    return 0;
}

int absoluteValue(int num) {
    return num < 0 ? -num : num;
}
100


Example04:

int signOf(int num) {
//    if (num < 0)
//        return -1;
//    else if (num == 0)
//        return 0;
//    else
//        return 1;
    return num > 0 ? 1 : (num == 0 ? 0 : -1);
}


Demonstration:

// 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