OPERATOR PRECEDENCE & ASSOCIATIVITY - C-Tutorial

Latest

Saturday, 19 November 2016

OPERATOR PRECEDENCE & ASSOCIATIVITY

OPERATOR PRECEDENCE & ASSOCIATIVITY


In programming languages, expressions are evaluated based on precedence and associativity of the operators.

Precedence: If more than one operator is available in a single statement, order of evaluation depends on precedence of operators.  Precedence refers to rank of operators that follow order of evaluation.

Compiler follows order of evaluation as:

Highest precedence operator is evaluated first before the lowest precedence operator.
If two or more operators have same precedence, it follows associativity.

Example: X = 2;
Y = X + 10 * 2;

=   +   *

Y = X + 20

=   +

Y = 22


Associativity: Associativity refers to the direction of evaluations as from left to right or from right to left.
Left-to-Right associativity evaluates the expression by starting on the left and moving to the right.

Example: 3 * 8 / 4 % 4 * 5

* / % * L → R

24 / 4 % 4 * 5

/ % * L → R

6 % 4 * 5

% * L → R

2 * 5

*
10

Right-to-Left associativity evaluates the expression by starting on the right and moving to the left.

Example: Assume a = 8, b = 5 and c = 8

a += b *= c -= 5
+=    *=    -= R → L

a += b *= 3
*=    -= R → L

a += 15
+=

a = 23


Operator precedence & Associatity Table:

RANK
OPERATOR
ASSOCIATIVITY

1
( ) [ ] -> . ++ (POSTFIX)
- - (POSTFIX)
L to R
2
++ (PREFIX) - - (PREFIX) ! ~ sizeof unary minus &(Address) *(Pointer)
R to L
3
 */ %
L to R
4
+ -
L to R
5
<<       >>
L to R
6
<   <=    >    >=
L to R
7
== !=
L to R
8
&
L to R
9
^
L to R
10
|
L to R
11
&&
L to R
12
||
L to R
13
?:
R to L
14
= += -= *= /= %= >>= <<= &= ^= |=
R to L
15
, (comma operator)
L to R

Solve the following expressions

1. Z = ++X + Y-- - ++Y - X-- - X-- - ++Y - X—
Where X = 7 and Y = -3

Solution: X = 5, Y = -2 and Z = -15

2. Z = X++ + ++Y - X-- + --Y
Where X = 7 and Y = 9

Solution: X = 7, Y = 9 and Z = 18

/* EXAMPLE PROGRAM */

#include<stdio.h>
#include<conio.h>
main()
{
int a=9,b=12,c=3,x;
clrscr();
x=a-b/3+c*2-1;
printf("\n X=%d",x);
getch();
}

No comments:

Post a Comment