🔀 Ternary (Conditional) Operator

Last Updated: Jan 2026


The Ternary Operator is a short way to write if...else conditions in one line. It checks a condition and returns one of two values based on whether it's true or false.

Syntax

condition ? value_if_true : value_if_false;

condition ? if_true_another_condition ? value_if_true_another_condition : value_if_false_another_condition : value_if_false;

If the condition is true → returns the first value.If false → returns the second value.


Example Basic

int age = 18;
char *result = (age >= 18) ? "You can vote" : "You cannot vote";
printf(result); // Output: You can vote

Example Nested

int marks = 85;
char *grade = marks >= 90 ? "A+" : marks >= 75 ? "A" : marks >= 50 ? "B" : "Fail";

printf(grade); // Output: A

👨‍💻 Quick Practice

  1. Check if a number is even or odd using a ternary operator.
  2. Print "Pass" if marks ≥ 40 else "Fail".
  3. Create a variable isLoggedIn and print "Logout" if true else "Login".
  4. Make a nested ternary for temperature: 30 → "Hot", 15-30 → "Warm", else → "Cold".

Liked This Tutorial

Scan QR Code To Leave A Review Or

Click Here To Leave A Review
Scan QR