The Ternary Operator
In this page:
The Ternary Operator
The ternary operator condition ? valueIfTrue : valueIfFalse is a compact one-line alternative to a simple if/else. It always evaluates to exactly one of its two branches. Ternary expressions can be nested but doing so hurts readability quickly.
Note: Use ternary for short, simple value selection — fall back to if/else once logic gets complex.
Example: The Ternary Operator
using System;
class Program
{
static void Main(string[] args)
{
int age = 16;
string status = age >= 18 ? "adult" : "minor";
Console.WriteLine(status);
Console.WriteLine(age % 2 == 0 ? "even" : "odd");
}
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: