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

bookTernary Operator

There's a shorthand for the if-else statement known as the ternary operator.

(condition) ? value_if_true : value_if_false

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:

main.c

main.c

copy
12345
int a = 10; int b = 4; int c; c = (a > b) ? a : b;

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.

main.c

main.c

copy
123456
if (a > b) { c = a; } else { c = b; }
Note
Note

While the ternary operator is a concise way to express conditionals, it's best to avoid it in too complex structures.

question mark

Which expression assigns the larger of x and y to max using the ternary operator?

Select the correct answer

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 4. Kapitel 3

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Suggested prompts:

What are the values of the variables involved in the ternary operation?

Can you show the full code example for context?

Can you explain how the ternary operator works in this case?

Awesome!

Completion rate improved to 2.63

bookTernary Operator

Svep för att visa menyn

There's a shorthand for the if-else statement known as the ternary operator.

(condition) ? value_if_true : value_if_false

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:

main.c

main.c

copy
12345
int a = 10; int b = 4; int c; c = (a > b) ? a : b;

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.

main.c

main.c

copy
123456
if (a > b) { c = a; } else { c = b; }
Note
Note

While the ternary operator is a concise way to express conditionals, it's best to avoid it in too complex structures.

question mark

Which expression assigns the larger of x and y to max using the ternary operator?

Select the correct answer

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 4. Kapitel 3
some-alt