What is Ternary Operator in C: Simple Explanation and Example
ternary operator in C is a compact way to write an if-else statement in a single line. It uses the syntax condition ? expression1 : expression2, where it evaluates the condition and returns expression1 if true, or expression2 if false.How It Works
The ternary operator in C works like a quick decision maker. Imagine you want to choose between two options based on a yes/no question. Instead of writing a full if-else block, the ternary operator lets you write this choice in one line.
It looks like this: condition ? value_if_true : value_if_false. First, it checks the condition. If the condition is true, it picks the first value; if false, it picks the second. This is like asking, "Is it raining?" If yes, take an umbrella; if no, wear sunglasses.
This operator is called "ternary" because it uses three parts: the condition, the true result, and the false result.
Example
This example shows how to use the ternary operator to find the bigger of two numbers and print it.
#include <stdio.h> int main() { int a = 10, b = 20; int max = (a > b) ? a : b; printf("The bigger number is %d\n", max); return 0; }
When to Use
Use the ternary operator when you want to write simple if-else decisions in a short and clear way. It is great for assigning values based on a condition without writing multiple lines.
For example, you can use it to set a status message, choose between two numbers, or decide which function to call. However, avoid using it for complex conditions or multiple nested decisions, as that can make your code hard to read.
Key Points
- The ternary operator is a shorthand for
if-elsestatements. - It uses three parts: condition, true result, and false result.
- It helps write concise and readable code for simple decisions.
- Not suitable for complex or nested conditions.