Followers

Friday, November 17, 2023

Operator precedence and associativity with examples in C language.

 

Example 1: Operator Precedence

Consider the expression:
int
result = 5 * 3 + 4 / 2 - 1;

To evaluate this expression, we follow the operator precedence:

  1. * (multiplication) has higher precedence than + (addition) and / (division).
  2. / (division) has the same precedence as *, but the associativity is left-to-right.

So, the evaluation order is:

  1. 5 * 3 (multiplication) => 15
  2. 4 / 2 (division) => 2
  3. 15 + 2 (addition) => 17
  4. 17 - 1 (subtraction) => 16

Therefore, the value of result is 16.

Example 2: Operator Associativity

Consider the expression:

int result = 10 / 2 / 2;

The / operator has left-to-right associativity, so the expression is equivalent to:

int result = (10 / 2) / 2;

The evaluation order is:

  1. 10 / 2 (division) => 5
  2. 5 / 2 (division) => 2

Therefore, the value of result is 2.

Example 3: Parentheses Override Precedence

Parentheses can be used to override the default precedence. Consider the expression:

int result = (5 + 3) * 4 / 2 - 1;

Here, the addition inside the parentheses has higher precedence, so the evaluation order is:

  1. (5 + 3) (addition inside parentheses) => 8
  2. 8 * 4 (multiplication) => 32
  3. 32 / 2 (division) => 16
  4. 16 - 1 (subtraction) => 15

Therefore, the value of result is 15.

Understanding operator precedence and associativity is essential for writing expressions that produce the intended results. It's a fundamental aspect of the C language syntax.

No comments:

Post a Comment