Important Notice:

Operator Precedence and Associativity

Operator Precedence and Associativity

29 views 1 min read

Operator Precedence and Associativity :-  Operator Precedence (ऑपरेटर प्राथमिकता) :-

जब किसी expression में एक से ज्यादा ऑपरेटर एक साथ इस्तेमाल होते हैं, तो कंपाइलर को यह तय करना होता है कि कौन सा ऑपरेटर पहले evaluate होगा। इसी नियम को Operator Precedence कहते हैं।

English-

When an expression contains more than one operator, the compiler must decide which operator gets evaluated first. This set of rules is called Operator Precedence.

Example-

 a = 10 + 5 * 2;
print(a)

यहाँ * (multiplication) की precedence + (addition) से ज्यादा होती है, इसलिए पहले 5 * 2 = 10 होगा, फिर 10 + 10 = 20 होगा।

➡️ Result: a = 20 (न कि 30)

मुख्य बिंदु:

  • हर ऑपरेटर की एक निश्चित precedence level (रैंक) होती है।
  • High precedence वाला ऑपरेटर पहले evaluate होता है।
  • Precedence सिर्फ यह बताती है कि "कौन पहले", यह नहीं बताती कि "किस दिशा में"

Operator Associativity (ऑपरेटर सहचारिता) :-

जब किसी expression में समान precedence वाले दो या दो से ज्यादा ऑपरेटर एक साथ आते हैं, तब यह तय करना ज़रूरी होता है कि evaluation किस दिशा (direction) में होगी — बाएं से दाएं (Left to Right) या दाएं से बाएं (Right to Left)। इसी को Associativity कहते हैं।

English

When two or more operators of equal precedence appear together in an expression, we need a rule to decide the direction of evaluation — Left to Right or Right to Left. This rule is called Associativity.

उदाहरण (Left to Right):

 a = 20 / 4 * 2
print(a)

/ और * दोनों की precedence बराबर है, और इनकी associativity Left to Right होती है। इसलिए: पहले 20 / 4 = 5, फिर 5 * 2 = 10

➡️ Result: a = 10

 

Related Notes