Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Ternary Operator | Introduction to Program Flow
C++ Introduction

book
Ternary Operator

The ternary operator offers a concise alternative to the if...else statement, with a notable distinction. It consists of three key elements:

h

ternary

copy
(boolean expression) ? instruction_for_true_case : instruction_for_false_case
1
(boolean expression) ? instruction_for_true_case : instruction_for_false_case

Such an operator is convenient to use, for example, when comparing two numbers:

cpp

main

copy
#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;
}
123456789101112
#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.

cpp

main

copy
#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;
}
123456789101112131415
#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; }

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 4. Chapter 2

Ask AI

expand
ChatGPT

Ask anything or try one of the suggested questions to begin our chat

some-alt