Example 1: Operator Precedence
Consider the expression:
int result = 5 * 3 + 4 / 2 - 1;
To evaluate this expression, we follow the operator precedence:
*(multiplication) has higher precedence than+(addition) and/(division)./(division) has the same precedence as*, but the associativity is left-to-right.
So, the evaluation order is:
5 * 3(multiplication) => 154 / 2(division) => 215 + 2(addition) => 1717 - 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:
10 / 2(division) => 55 / 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:
(5 + 3)(addition inside parentheses) => 88 * 4(multiplication) => 3232 / 2(division) => 1616 - 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