0
0
Cprogramming~5 mins

Ternary operator in C

Choose your learning style9 modes available
Introduction

The ternary operator lets you choose between two values quickly based on a condition. It makes simple if-else decisions shorter and easier to write.

When you want to assign a value based on a quick yes/no question.
When you want to print one of two messages depending on a condition.
When you want to return a value from a function based on a simple check.
Syntax
C
condition ? value_if_true : value_if_false;

The condition is checked first.

If condition is true, the expression returns value_if_true, otherwise it returns value_if_false.

Examples
Assigns the bigger of a or b to max.
C
int a = 10, b = 20;
int max = (a > b) ? a : b;
Sets result to "Even" if num is even, otherwise "Odd".
C
int num = 5;
char* result = (num % 2 == 0) ? "Even" : "Odd";
Prints "Equal" if a equals b, else prints "Not equal".
C
printf("%s\n", (a == b) ? "Equal" : "Not equal");
Sample Program

This program checks if age is 18 or more. If yes, it sets can_vote to "Yes", otherwise "No". Then it prints the answer.

C
#include <stdio.h>

int main() {
    int age = 18;
    char* can_vote = (age >= 18) ? "Yes" : "No";
    printf("Can vote? %s\n", can_vote);
    return 0;
}
OutputSuccess
Important Notes

The ternary operator is a shortcut for simple if-else statements.

Use it only for simple conditions to keep code readable.

Both value_if_true and value_if_false must be expressions that return a value.

Summary

The ternary operator chooses between two values based on a condition.

It is written as condition ? value_if_true : value_if_false.

Use it to make your code shorter and clearer for simple decisions.