Topic 15 of 83
Ternary Operator
Overview
The ternary operator (`? :`) is a shorthand for simple if-else statements. It makes code concise when assigning a value based on a condition.
Syntax
cpp
int a = 10, b = 20;
// Syntax: condition ? value_if_true : value_if_false;
int maxVal = (a > b) ? a : b;
string status = (a >= 18) ? "Adult" : "Minor";Common Pitfalls
- Nesting ternary operators makes code incredibly hard to read and should generally be avoided.
- Ensure both the true and false return values are of the same or compatible data types.
Interview Tips
- The ternary operator is an expression, meaning it evaluates to a value. An if-else is a statement. This means you can use the ternary operator inline during variable initialization.
Real-World Example
Setting inline default values.
example
cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
bool isLoggedIn = true;
// Inline usage
cout << "Welcome, " << (isLoggedIn ? "User" : "Guest") << "!" << endl;
return 0;
}