HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

Short Hand If...Else (Ternary Operator)

In programming, a short-hand if...else, also known as the ternary operator, is a compact way to write conditional statements. It condenses an if-else statement into a single line of code, making your code more concise and readable.

Syntax

variable = (condition) ? expressionTrue : expressionFalse;


Instead of writing:


Example

#include <stdio.h>

int main() {

int time = 20;

if (time < 18) {

printf("Good day.");

} else {

printf("Good evening.");

}

return 0;

}


Output

Good evening.


You can simply write:

Example

#include <stdio.h>

int main() {

int time = 20;

(time < 18) ? printf("Good day.") : printf("Good evening.");

return 0;

}


Output

Good evening.