Ternary 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
12345int 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
123456if (a > b) { c = a; } else { c = b; }
While the ternary operator is a concise way to express conditionals, it's best to avoid it in too complex structures.
Takk for tilbakemeldingene dine!
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår
Awesome!
Completion rate improved to 2.63
Ternary Operator
Sveip for å vise menyen
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
12345int 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
123456if (a > b) { c = a; } else { c = b; }
While the ternary operator is a concise way to express conditionals, it's best to avoid it in too complex structures.
Takk for tilbakemeldingene dine!