Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Ternary Operator | Control Statements
C Basics

Ternary OperatorTernary Operator

The Ternary Operator in C

In C, there's a shorthand for the if-else statement known as the ternary operator, represented by ?:.

You can use this operator when you want to assign one of two values to a variable based on a condition. For instance, to determine the larger of two variables:

After executing the above statement, what will be the value of c?

For comparison, here's how the same logic looks using the if...else statement:

Note

While the ternary operator is a concise way to express conditionals, it's best to avoid it in complex structures. It can make the code harder to read for your teammates (though perhaps not for your instructor).

Everything was clear?

Section 4. Chapter 3
course content

Course Content

C Basics

Ternary OperatorTernary Operator

The Ternary Operator in C

In C, there's a shorthand for the if-else statement known as the ternary operator, represented by ?:.

You can use this operator when you want to assign one of two values to a variable based on a condition. For instance, to determine the larger of two variables:

After executing the above statement, what will be the value of c?

For comparison, here's how the same logic looks using the if...else statement:

Note

While the ternary operator is a concise way to express conditionals, it's best to avoid it in complex structures. It can make the code harder to read for your teammates (though perhaps not for your instructor).

Everything was clear?

Section 4. Chapter 3
some-alt