Ternary Conditional Operator
Part of the Fundamentals section of Coddy's C journey — lesson 29 of 63.
The ternary conditional operator is a shorthand way to express an if-else statement in a single line.
The syntax is:
condition ? value_if_true : value_if_false;Let's look at an example. First, here's a traditional if-else statement:
int max;
if (a > b) {
max = a;
} else {
max = b;
}Now, let's rewrite it using the ternary operator:
int max = (a > b) ? a : b;In this example:
a > bis the condition- If the condition is true,
ais returned - If the condition is false,
bis returned
The ternary operator can also be nested, but this can make code harder to read:
int x = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);Challenge
EasyCreate a program that checks if a number is positive, negative, or zero using the conditional operator. The program should:
- Take an integer input from the user.
- Use the conditional operator to determine if the number is positive, negative, or zero.
- Print the result in the format:
"The number is [positive/negative/zero]".
Cheat sheet
The ternary conditional operator provides a shorthand way to express an if-else statement in a single line.
Syntax:
condition ? value_if_true : value_if_false;Example comparing traditional if-else with ternary operator:
// Traditional if-else
int max;
if (a > b) {
max = a;
} else {
max = b;
}
// Ternary operator
int max = (a > b) ? a : b;The ternary operator can be nested, though this reduces readability:
int x = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);Try it yourself
#include <stdio.h>
int main() {
int number;
scanf("%d", &number);
// Write your code below
char* result =
printf("The number is %s\n", result);
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Control Flow
If StatementIf - ElseElse-IfSwitch CaseTernary Conditional OperatorRecap ChallengeNested If - Else3Operators
Arithmetic OperatorsModulo OperatorIncrement/DecrementAssignment OperatorsRelational OperatorsLogical Operators Part 1Logical Operators Part 2Logical Operators Part 3Recap Challenge