Course Content
C++ Introduction
4. Introduction to Program Flow
5. Introduction to Functions
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:
- Boolean expression;
- Instructions for the
true
case; - Instructions for the
false
case.
Such an operator is convenient to use, for example, when comparing two numbers:
main.cpp
In this case, the outcome of the ternary operation has been assigned to the result
variable.
When the comparison returns a true result, the value of var1
will be stored in the result
variable.
![](https://codefinity-content-media.s3.eu-west-1.amazonaws.com/59a3e4eb-a3a1-49a4-ba70-da98e8fee510/true.png)
Conversely, if the comparison result is false, to the result
variable will be assigned the value of the var2
variable.
![](https://codefinity-content-media.s3.eu-west-1.amazonaws.com/59a3e4eb-a3a1-49a4-ba70-da98e8fee510/false.png)
Note
Observe data type compatibility!
How it would look like using if...else
:
main.cpp
Everything was clear?
Course Content
C++ Introduction
4. Introduction to Program Flow
5. Introduction to Functions
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:
- Boolean expression;
- Instructions for the
true
case; - Instructions for the
false
case.
Such an operator is convenient to use, for example, when comparing two numbers:
main.cpp
In this case, the outcome of the ternary operation has been assigned to the result
variable.
When the comparison returns a true result, the value of var1
will be stored in the result
variable.
![](https://codefinity-content-media.s3.eu-west-1.amazonaws.com/59a3e4eb-a3a1-49a4-ba70-da98e8fee510/true.png)
Conversely, if the comparison result is false, to the result
variable will be assigned the value of the var2
variable.
![](https://codefinity-content-media.s3.eu-west-1.amazonaws.com/59a3e4eb-a3a1-49a4-ba70-da98e8fee510/false.png)
Note
Observe data type compatibility!
How it would look like using if...else
:
main.cpp
Everything was clear?