← Back to C Course | Chapter 3: Operators | Lesson 8 of 9

C Ternary Operator

What is the Ternary Operator?

The ternary operator condenses a simple if-else into one expression using the syntax condition ? valueIfTrue : valueIfFalse, which is especially handy when you just need to pick between two values rather than run different blocks of statements.

Example: What is the Ternary Operator?

c
#include <stdio.h>
int main() {
	int age = 20;
	char *status = (age >= 18) ? "Adult" : "Minor";
	printf("%s", status);
	return 0;
}

Finding the Maximum

Finding the larger of two numbers can be written in one line as max = (a > b) ? a : b;, avoiding a full four-line if-else block for what's fundamentally a simple choice between two values.

Example: Finding the Maximum

c
#include <stdio.h>
int main() {
	int a = 7, b = 12;
	int max = (a > b) ? a : b;
	printf("%d", max);
	return 0;
}

Pass or Fail Check

For binary outcomes like pass/fail, the ternary operator lets you compute a result directly: result = (score >= 50) ? "Pass" : "Fail";, keeping the logic compact and readable in a single assignment.

Example: Pass or Fail Check

c
#include <stdio.h>
int main() {
	int score = 65;
	char *result = (score >= 50) ? "Pass" : "Fail";
	printf("%s", result);
	return 0;
}

Even or Odd

Combining n % 2 == 0 with the ternary operator lets you classify a number as even or odd in a single expression, such as label = (n % 2 == 0) ? "Even" : "Odd";, without a separate if statement.

Example: Even or Odd

c
#include <stdio.h>
int main() {
	int n = 7;
	char *label = (n % 2 == 0) ? "Even" : "Odd";
	printf("%s", label);
	return 0;
}

Nested Ternary

You can nest ternary operators to handle more than two outcomes, but each level of nesting makes the expression harder to read at a glance -- past two conditions, a regular if-else ladder is usually clearer.

Example: Nested Ternary

c
#include <stdio.h>
int main() {
	int score = 75;
	char *grade = (score >= 90) ? "A" : (score >= 70) ? "B" : "C";
	printf("%s", grade);
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.