Course Content
C++ Introduction
C++ Introduction
Ternary Operator
The ternary operator offers a concise alternative to the if...else
statement, with a notable distinction. It consists of three key elements:
ternary
(boolean expression) ? instruction_for_true_case : instruction_for_false_case
Such an operator is convenient to use, for example, when comparing two numbers:
main
#include <iostream> int main() { int accountBalance = 5000; // Account balance int minimumBalance = 1000; // Minimum required balance // Use the ternary operator to check if the balance is above the minimum required int result = (accountBalance > minimumBalance) ? accountBalance : minimumBalance; std::cout << "Account balance: " << result << std::endl; }
In this case, the outcome of the ternary operation is assigned to the result
variable. If the comparison returns true, the value of var1
will be stored in the result
variable.
Conversely, if the comparison result is false, to the result
variable will be assigned the value of the var2
variable.
The ternary operator is preferred for simple conditional assignments due to its conciseness, allowing you to check a condition and assign a value in one line. In contrast, if...else
is more verbose and requires multiple lines, making it less efficient for simple logic.
main
#include <iostream> int main() { int accountBalance = 5000; // Account balance int minimumBalance = 1000; // Minimum required balance int result; if (accountBalance > minimumBalance) result = accountBalance; else result = minimumBalance; std::cout << "Account balance: " << result << std::endl; }
Thanks for your feedback!