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
course content

Contenido del Curso

C++ Introduction

Ternary OperatorTernary Operator

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

  1. Boolean expression;
  2. Instructions for the true case;
  3. Instructions for the false case.

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

cpp

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.

Conversely, if the comparison result is false, to the result variable will be assigned the value of the var2 variable.

Note

Observe data type compatibility!

How it would look like using if...else:

cpp

main.cpp

What will be written to the result variable?

Selecciona la respuesta correcta

¿Todo estuvo claro?

Sección 4. Capítulo 2
course content

Contenido del Curso

C++ Introduction

Ternary OperatorTernary Operator

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

  1. Boolean expression;
  2. Instructions for the true case;
  3. Instructions for the false case.

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

cpp

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.

Conversely, if the comparison result is false, to the result variable will be assigned the value of the var2 variable.

Note

Observe data type compatibility!

How it would look like using if...else:

cpp

main.cpp

What will be written to the result variable?

Selecciona la respuesta correcta

¿Todo estuvo claro?

Sección 4. Capítulo 2
some-alt