Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Short Forms | Conditional Statements
Introduction to C++ | Mobile-Friendly

book
Short Forms

It's pretty easy to get confused by these expressions. To make code more readable you can use the short version of these statements or also called ternary operator, since it consists of three operands. The syntax is the following:

python
variable = (condition) ? expression#1 : expression#2;

First expression will be executed if the condition returns true, second - if the condiction returns false. Let’s look at the example:

// Define variables
int x = 3;
int y = 7;

// Check conditions
string result1 = (x < 5) ? "x is less than 5." : "x is greater than 5.";
string result2 = (y < 5) ? "y is less than 5." : "y is greater than 5.";

// Print results
cout << result1 << endl;
cout << result2 << endl;
1234567891011
// Define variables int x = 3; int y = 7; // Check conditions string result1 = (x < 5) ? "x is less than 5." : "x is greater than 5."; string result2 = (y < 5) ? "y is less than 5." : "y is greater than 5."; // Print results cout << result1 << endl; cout << result2 << endl;
copy

In the first line where we check conditions the statement returns true and we assign to the variable first expression. In the second line the statement returns false and we assign second expression.

question-icon

Try to write the task about buying alcohol in America using the short form:

string result =
_ _ _
_ _ _
"You can buy alcohol."
_ _ _
"You can't buy alcohol.";

Натисніть або перетягніть елементи та заповніть пропуски

dots
if
dots
(age >= 21)
dots
:
dots
=
dots
?
dots
(age <= 21)

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 3. Розділ 6
some-alt