🔄 C++ Ternary Operator – Shortcut for if-else
The ternary operator is a shorthand for the if-else statement. It’s like a quick decision-maker, all in one line! ⏱️
🧮 Syntax of the Ternary Operator
The basic syntax is:
condition ? expression_if_true : expression_if_false;
It works like this:
- If the condition is true, the first expression is executed.
- If the condition is false, the second expression is executed.
🔧 Example: Using the Ternary Operator
#include <iostream> using namespace std; int main() { int a = 5, b = 10; // Using ternary operator to compare a and b string result = (a > b) ? "a is greater" : "b is greater"; cout << result << endl; // Will print "b is greater" return 0; }
💡 Why Use It?
The ternary operator is great for:
- Shortening simple if-else conditions.
- Making your code more concise and readable.
- Simple decisions where you don’t want to write a full if-else block.
It’s a real time-saver when you need to make quick decisions! ⏳