C++ Operator Precedence

πŸ“Š C++ Operator Precedence

Operator Precedence decide karta hai ki expression mein kaunsa operator pehle execute hoga.
Agar precedence same ho, to associativity decide karti hai order.


πŸ”Ή 1. Example (Without Parentheses)

int result = 10 + 5 * 2;
cout << result;

Output:

20

πŸ‘‰ Pehle * (multiplication), phir +


πŸ”Ή 2. Example (With Parentheses)

int result = (10 + 5) * 2;
cout << result;

Output:

30

πŸ‘‰ Parentheses () ki highest priority hoti hai.


πŸ”Ή 3. Common Operator Precedence Table (High β†’ Low)

Priority Operator
1️⃣ ()
2️⃣ ++ -- (Unary)
3️⃣ * / %
4️⃣ + -
5️⃣ < <= > >=
6️⃣ == !=
7️⃣ &&
8️⃣ `
9️⃣ = += -= etc

πŸ”Ή 4. Associativity

Operator Associativity
+ - * / % Left β†’ Right
= Right β†’ Left
++ -- (prefix) Right β†’ Left

πŸ”Ή 5. Example with Associativity

int a = 5, b = 10, c = 15;
a = b = c;
cout << a;

Output:

15

πŸ‘‰ Assignment (=) right to left evaluate hota hai.


πŸ”Ή 6. Logical Operator Precedence

bool result = true || false && false;
cout << result;

Output:

1

πŸ‘‰ && pehle, phir ||


πŸ”Ή 7. Best Practice βœ…

❌ Confusing:

int x = a + b * c - d / e;

βœ” Clear:

int x = a + (b * c) - (d / e);

❌ Common Mistake

if (a > b && c < d || e == f) // confusing

βœ” Better:

if ((a > b && c < d) || e == f)

πŸ“Œ Summary

  • Parentheses () highest priority

  • * / % before + -

  • && before ||

  • Use parentheses for clarity

You may also like...