C++ Short Hand If Else

⚡ C++ Short Hand If Else (Ternary Operator)

C++ mein Short Hand if-else ko Ternary Operator kehte hain.
Ye simple conditions ke liye if…else ka short form hota hai.


🔹 1. Syntax

condition ? expression_if_true : expression_if_false;

🔹 2. Basic Example

int a = 10, b = 20;

string result = (a > b) ? “A is greater” : “B is greater”;
cout << result;


🔹 3. Number Example

int num = 5;

string type = (num % 2 == 0) ? “Even” : “Odd”;
cout << type;


🔹 4. Assign Value Using Ternary

int age = 16;

bool isAdult = (age >= 18) ? true : false;
cout << isAdult;


🔹 5. Without Storing (Direct Print)

int marks = 45;

cout << (marks >= 40 ? “Pass” : “Fail”);


🔹 6. Multiple Conditions ❌ (Avoid)

int x = 0;

string result = (x > 0) ? “Positive” : (x < 0) ? “Negative” : “Zero”;

⚠️ Works, but readability poor.

✔ Better:

if (x > 0)
cout << "Positive";
else if (x < 0)
cout << "Negative";
else
cout << "Zero";

🔹 7. Ternary vs if-else

Ternaryif-else
Short & compactClear & readable
Single condition bestMultiple conditions
Expression basedStatement based

❌ Common Mistakes

(a > b) ? cout << a : cout << b; // ❌ wrong

✔ Correct:

cout << ((a > b) ? a : b);

📌 Summary

  • Short hand if-else = ternary operator

  • Use for simple conditions only

  • Syntax: condition ? true : false

  • Avoid nested ternary for readability

You may also like...