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

Course Content

C++ Introduction

C++ Introduction

1. Getting Started
2. Introduction to Operators
3. Variables and Data Types
4. Introduction to Program Flow
5. Introduction to Functions

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
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
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
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
We're sorry to hear that something went wrong. What happened?
some-alt