Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C/C++ Ternary Operator
The ternary operator (?:) in C/C++ is a shorthand for an if-else statement. It is the only operator in C/C++ that takes three operands, which is why it is called "ternary".
Syntax
(expression-1) ? expression-2 : expression-3
This operator returns one of two values depending on the result of an expression. If expression-1 evaluates to Boolean true, then expression-2 is evaluated and its value is returned as the final result. Otherwise, expression-3 is evaluated and its value is returned.
Example − Finding Maximum of Two Numbers
Let us write a program to find the maximum of two numbers using the ternary operator −
#include <iostream>
using namespace std;
int main() {
int a = 10;
int b = 20;
int max = a > b ? a : b;
cout << "Maximum value = " << max << "\n";
return 0;
}
The output of the above code is −
Maximum value = 20
If we compare the syntax with the above example −
-
expression-1is(a > b) -
expression-2isa -
expression-3isb
First, the expression a > b is evaluated, which results in false since 10 is not greater than 20. Hence the value of b (20) is returned and assigned to max.
Example − Checking Even or Odd
The ternary operator can also return strings or other expressions −
#include <iostream>
using namespace std;
int main() {
int num = 15;
string result = (num % 2 == 0) ? "Even" : "Odd";
cout << num << " is " << result << endl;
return 0;
}
The output of the above code is −
15 is Odd
Example − Nested Ternary Operator
Ternary operators can be nested to handle multiple conditions, similar to if-else if-else chains −
#include <iostream>
using namespace std;
int main() {
int a = 30, b = 30;
string result = (a > b) ? "a is greater"
: (a < b) ? "b is greater"
: "both are equal";
cout << result << endl;
return 0;
}
The output of the above code is −
both are equal
Note − While nesting is possible, deeply nested ternary operators reduce readability. Use if-else statements for more than two conditions.
Ternary Operator vs if-else
| Feature | Ternary Operator | if-else Statement |
|---|---|---|
| Syntax | Single line expression | Multi-line block |
| Returns a value? | Yes ? can be used in assignments | No ? is a statement, not an expression |
| Readability | Good for simple conditions | Better for complex logic |
| Nesting | Possible but gets hard to read | Cleaner for multiple branches |
| Performance | Same (compiler optimizes both equally) | Same |
Conclusion
The ternary operator (?:) is a concise alternative to if-else for simple conditional assignments. It evaluates a condition and returns one of two values based on whether the condition is true or false. While it improves brevity for straightforward cases, use regular if-else for complex or nested conditions to maintain readability.
