Conditional operator allows us to do this:
if(!found_sig_fig) { // The input doesn't contain a nonzero number
return std::string(negative ? "-" : "") + "0e0";
}
and this:
std::cout << p1[i] << ((i != 15-1) ? ", " : " ");
// In this case, I wanted to print a "," for all elements, except the last one
Introduction
The conditional operator (?:) is also called the arithmetic if operator. It’s a ternary operator, meaning it requires 3 operands. Historically, it’s been C++’s only ternary operator.
It’s concise way of implementing an if/else block.
Syntax: condition ? true expression : false expression
Uses of the conditional operator
For all cases below, replacing it with an if/else would case additional LOC and clutter.
- Variable initialization
#include <iostream>
int main()
{
constexpr bool isMember { true };
constexpr double ticketPrice { isMember ? 12.50 : 18.00 };
std::cout << "Ticket price: $" << ticketPrice << '\\n';
}
2. Function call
#include <iostream>
void setMotorSpeed(int speedPercent)
{
std::cout << "Motor speed set to " << speedPercent << "%\\n";
}
int main()
{
constexpr bool batteryLow { true };
setMotorSpeed(batteryLow ? 40 : 100);
}
3. return statement and std::cout
See examples at the top
When should you use the condition operator?
- Initializing an object with one of two values
- Assigning one of two values to an object
- Passing one of two values to a function.
- Returning one of two values from a function.
- Printing one of two values.