0% found this document useful (0 votes)
9 views20 pages

Operator Precedence and Associativity in C

The document explains operator precedence and associativity in C programming, which dictate the order of evaluation in expressions. It provides examples and a precedence table, highlighting how different operators are evaluated based on their precedence and associativity. Additionally, it discusses infix, postfix, and prefix notations, emphasizing the efficiency of postfix and prefix for compiler operations.

Uploaded by

nisha langeh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views20 pages

Operator Precedence and Associativity in C

The document explains operator precedence and associativity in C programming, which dictate the order of evaluation in expressions. It provides examples and a precedence table, highlighting how different operators are evaluated based on their precedence and associativity. Additionally, it discusses infix, postfix, and prefix notations, emphasizing the efficiency of postfix and prefix for compiler operations.

Uploaded by

nisha langeh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

OPERATOR PRECEDENCE AND ASSOCIATIVITY IN C

Operator precedence and associativity are rules that decide the order in which
parts of an expression are calculated. Precedence tells us which operators should
be evaluated first, while associativity determines the direction (left to right or
right to left) in which operators with the same precedence are evaluated.
Let’s take a look at an example:
#include <stdio.h>

int main() {
int a = 6, b = 3, c = 4;
int res;

// Precedence and associativity applied here


res = a + b * c / 2;

printf("%d", res);

return 0;
}

Output
12
Explanation: The above expression is evaluated as 6 + ( (3 * 4) / 2) = 16, not (6 +
3) * (4 / 2) = 18. So what guided the compiler to evaluate the expression in this
way? It is actually the precedence and associativity of the operators used in this
expression.
In this article, let’s discuss operator precedence, operator associativity, and the
precedence table that determines the priority of operators in expressions in C
language.
Operator Precedence
Operator precedence determines which operation is performed first in an
expression with more than one operator with different precedence. Let’s try to
evaluate the following expression,
10 + 20 * 30
The expression contains two operators, + (addition) and * (multiplication).
According to operator precedence, multiplication (*) has higher precedence than
addition (+), so multiplication is checked first. After evaluating multiplication, the
addition operator is then evaluated to give the final result.

We can verify this using the following C program


#include <stdio.h>

int main() {

// Printing the value of same expression


printf("%d", 10 + 20 * 30);

return 0;
}
Output
610
As we can see, the expression is evaluated as,10 + (20 * 30) but not as (10 + 20) *
30 due to * operator having higher precedence.
Operator Associativity
Operator associativity is used when two operators of the same precedence
appear in an expression. Associativity can be either from Left to Right or Right to
Left. Let’s evaluate the following expression,
100 / 5 % 2
The division (/) and modulus (%) operators have the same precedence, so the
order in which they are evaluated depends on their left-to-right associativity. This
means the division is performed first, followed by the modulus operation. After
the calculations, the result of the modulus operation is determined.

We can verify the above using the following C program:


#include <stdio.h>
int main() {
// Verifying the result of the same expression
printf("%d", 100 / 5 % 2);

return 0;
}

Output
0
Operators Precedence and Associativity are two characteristics of operators that
determine the evaluation order of sub-expressions.
Example of Operator Precedence and Associativity
In general, operator precedence and associativity are applied together in
expressions. Consider the expression exp = 100 + 200 / 10 – 3 * 10, where the
division (/) and multiplication (*) operators have the same precedence but are
evaluated before addition (+) and subtraction (-). Due to left-to-right associativity,
the division is evaluated first, followed by multiplication. After evaluating the
division and multiplication, the addition and subtraction are evaluated from left to
right, giving the final result.

Again, we can verify this using the following C program.


#include <stdio.h>
int main() {

// getting the result of the same expression as the


// example
int exp = 100 + 200 / 10 - 3 * 10;
printf("%d", exp);

return 0;
}

Output
90
Operator Precedence and Associativity Table
The following tables list the C operator precedence from highest to lowest and the
associativity for each of the operators:

Operator
Precedence Description Associativity

() Parentheses (function call)

Array Subscript (Square


[]
Brackets)

1 Left-to-Right
. Dot Operator

-> Structure Pointer Operator

++ , — Postfix increment, decrement


Operator
Precedence Description Associativity

++ / — Prefix increment, decrement

+/– Unary plus, minus

Logical NOT, Bitwise


!,~
complement

2 Right-to-Left
(type) Cast Operator

* Dereference Operator

& Addressof Operator

sizeof Determine size in bytes

Multiplication, division,
3 *,/,% Left-to-Right
modulus

4 +/- Addition, subtraction Left-to-Right

Bitwise shift left, Bitwise shift


5 << , >> Left-to-Right
right

6 < , <= Relational less than, less than Left-to-Right


Operator
Precedence Description Associativity

or equal to

Relational greater than,


> , >=
greater than or equal to

Relational is equal to, is not


7 == , != Left-to-Right
equal to

8 & Bitwise AND Left-to-Right

9 ^ Bitwise exclusive OR Left-to-Right

10 | Bitwise inclusive OR Left-to-Right

11 && Logical AND Left-to-Right

12 || Logical OR Left-to-Right

13 ?: Ternary conditional Right-to-Left

14 = Assignment Right-to-Left

+= , -= Addition, subtraction
Operator
Precedence Description Associativity

assignment

Multiplication, division
*= , /=
assignment

Modulus, bitwise AND


%= , &=
assignment

Bitwise exclusive, inclusive OR


^= , |=
assignment

Bitwise shift left, right


<<=, >>=
assignment

15 , comma (expression separator) Left-to-Right

Easy Trick to Remember the Operators Associtivity and Precedence: PUMA’S


REBL TAC
where, P = Postfix, U = Unary, M = Multiplicative, A = Additive, S = Shift, R =
Relational, E = Equality, B = Bitwise, L = Logical, T = Ternary, A = Assignment and C
= Comma
Important Points
There are a few important points and cases that we need to remember for
operator associativity and precedence which are as follows:
Associativity is only used when there are two or more operators of the same
precedence.
The point to note is associativity doesn’t define the order in which operands of a
single operator are evaluated. For example, consider the following program,
associativity of the + operator is left to right, but it doesn’t mean f1() is always
called before f2(). The output of the following program is in-fact compiler-
dependent.
// Associativity is not used in the below program.
// Output is compiler dependent.

#include <stdio.h>

int x = 0;
int f1()
{
x = 5;
return x;
}
int f2()
{
x = 10;
return x;
}
int main()
{
int p = f1() + f2();
printf("%d ", x);
return 0;
}

Output
10
You can check this article for more details.
We can use parenthesis to change the order of evaluation
Parenthesis ( ) got the highest priority among all the C operators. So, if we want to
change the order of evaluation in an expression, we can enclose that particular
operator in ( ) parenthesis along with its operands.
Example
Consider the given expression
100 + 200 / 10 – 3 * 10
= 90
But if we enclose 100 + 200 in parenthesis, then the result will be different.
(100 + 200) / 10 – 3 * 10 = 0
=0
As the + operator will be evaluated before / operator.
All operators with the same precedence have the same associativity.
This is necessary, otherwise, there won’t be any way for the compiler to decide
the evaluation order of expressions that have two operators of the same
precedence and different associativity. For example + and – have the same
associativity.
Precedence and associativity of postfix ++ and prefix ++ are different.
The precedence of postfix ++ is more than prefix ++, their associativity is also
different. The associativity of postfix ++ is left to right and the associativity of
prefix ++ is right to left
Comma has the least precedence among all operators and should be used
carefully.
For example, consider the following program, the output is 1.
#include <stdio.h>
int main()
{
int a;

// Evaluated as (a = 1), 2, 3
a = 1, 2, 3;
printf("%d", a);
return 0;
}

Output
1
There is no chaining of comparison operators in C
In Python, an expression like “c > b > a” is treated as “c > b and b > a”, but this type
of chaining doesn’t happen in C. For example, consider the following program. The
output of the following program is “FALSE”.
#include <stdio.h>
int main() {
int a = 10, b = 20, c = 30;

// (c > b > a) is treated as ((c > b) > a), associativity of '>'


// is left to right.
//Therefore the value becomes ((30 > 20) > 10)
// which becomes (1 > 10)
if (c > b > a)
printf("TRUE");
else
printf("FALSE");
return 0;
}

Output
FALSE
Conclusion
It is necessary to know the precedence and associativity for the efficient usage of
operators. It allows us to write clean expressions by avoiding the use of
unnecessary parenthesis. Also, it is the same for all the C compilers so it also
allows us to understand the expressions in the code written by other
programmers.
Also, when confused about or want to change the order of evaluation, we can
always rely on parenthesis ( ). The advantage of brackets is that the reader doesn’t
have to see the table to find out the order.
INFIX PREFIX POSTFIX CONVERSION (STACK)

Introduction
 Operation : Any Expression of algebraic format (Example : A + B)
 Operands : A and B or 5 & 6 are operands
 Operators : +. -, %,*,/ etc are operators
Infix Notation
Infix is the day to day notation that we use of format A + B type. The general
form can be classified as (a op b) where a and b are operands(variables)
and op is Operator.
 Example 1 : A + B
 Example 2 : A * B + C / D
Postfix Notation
Postfix is notation that compiler uses/converts to while reading left to right and
is of format AB+ type. The general form can be classified as (ab
op) where a and b are operands(variables) and op is Operator.
 Example 1 : AB+
 Example 2 : AB*CD/+
Prefix Notation
Prefix is notation that compiler uses/converts to while reading right to left
(some compilers can also read prefix left to right) and is of format +AB type. The
general form can be classified as (op ab) where a and b are operands(variables)
and op is Operator.
 Example 1 : +AB
 Example 2 : +*AB/CD
Why Postfix/Prefix Expressions are faster than Infix?
For Infix Expression which is format A+B*C, if the compiler is reading left to right
then it can’t evaluate A+B first until it has read whole expression and knows
expression is actually A + (B*C) i.e. B * C needs to be implemented first
Postfix for above infix is ABC*+. Now, as soon as compiler sees two operands
followed by operator it can implement it without caring for precedence.
 Assume ABC*+
 ABC*+ (BC* is implemented as B*C and result is put back)
 AX+ (Assuming X stores result of BC* i.e. B*C)
 Now finally AX+ can be implemented as A+X
Note Compiler converts our Infix Expression into postfix or Prefix as expressions
are operated as stacks and postfix and prefix are faster to implement as
compiler doesn't need to care about precedence at all.

Compiler converts infix expression to postfix/prefix at compile time, so at


runtime your calculations are always happening in post-prefix. A website's code
maybe compiled once a week but it may need to run 1 million times a week.

Which is why we prefer that runtime execution should be as fast as possible. If


calculations happen faster than we have optimized our page load time hugely
right?
Related Pages
Representation of a Stack as an Array
Representation of a Stack as a Linked List
Infix to Postfix Conversion
Infix to prefix conversion
Postfix to Prefix Conversion
Problem (This is how to convert manually for MCQ Question in the exam)
Problem
 Infix: a + b * c + d can be written as a + (b * c) + d
 Now, for all + – / * associativity is left to right we will write it as
 (a + (b * c)) + d and thus further ((a + (b * c)) + d)
 Solving and converting innermost bracket to postfix
 Step 1 –((a + bc*)+ d)
 Step 2 – Consider bc* as separate operand x the innermost bracket now
looks like ((a + x)+ d)
o Applying postfix it looks like – (ax+ + d)replacing x here (abc*+ + d)
 Step 3 – Consideringabc*+as separate operand z, the final bracket looks
like – (z + d)the result would be zd+
o replacing z value = abc*+d+
Alert
The above may give wrong results sometimes, which is why its always safer to
use below algorithm for both coding and manual calculation -

Infix to Postfix in C using Stacks


Infix to Postfix
Any operation can be expressed in Infix, postfix and prefix, we shall see how to
convert infix to prefix operation via manual calculation and via code. Lets have a
look at Infix to postfix conversion using stack in C
Infix to Postfix in C
 Infix – Any operation of format a op b format example a + b is called an infix
operation
 Postfix – An operation or expression can also be written in the format of a b
op i.e. a b + which is similar to writing a + b in infix. All we are doing is
shifting operator to the right of operands
Why we need postfix operator?
For a compiler, it is easier to read postfix or prefix operation. As a compiler either
reads from right to left or left to right.

Algorithm
1. First Start scanning the expression from left to right
2. If the scanned character is an operand, output it, i.e. print it
3. Else
o If the precedence of the scanned operator is higher than the
precedence of the operator in the stack(or stack is empty or has'(‘),
then push operator in the stack
o Else, Pop all the operators, that have greater or equal precedence
than the scanned operator. Once you pop them push this scanned
operator. (If we see a parenthesis while popping then stop and push
scanned operator in the stack)
4. If the scanned character is an ‘(‘, push it to the stack.
5. If the scanned character is an ‘)’, pop the stack and output it until a ‘(‘ is
encountered, and discard both the parenthesis.
6. Now, we should repeat the steps 2 – 6 until the whole infix i.e. whole
characters are scanned.
7. Print output
8. Do the pop and output (print) until stack is not empty
Infix to Prefix
Problem (This is how to convert manually for MCQ Question in the exam)
 Infix: (a / b + c) - ( d + e * f) can be written as ((a / b) + c) - ( d + (e * f))
 Now, we have done the above according to associativity
 Solving and converting innermost bracket to prefix
 Step 1 –(/ab + c) - ( d + *ef)
 Step 2 – Consider /ab and *ef as separate operand x and y
 the innermost bracket now looks like (x + c) - (d + y)
o Applying prefix it looks like – (+xc - +dy)replacing x and y
here (+/abc - +d*ef)
 Step 3 – Considering+/abc and+d*efas separate operand z and w, the final
bracket looks like – (z - w)the result would be -zw
o replacing z and w value = -+/abc+d*ef
Alert
The above may give wrong results sometimes, which is why its always safer to
use below algorithm for both coding and manual calculation -

Also note below algorithm is given wrong on Geeks4Geek website, only refer
from here.(As most codes are made by interns and PrepInsta pages are made by
Ph.D Teachers)
Algorithm (For Code/Manual Calculation)
Given Infix - ((a/b)+c)-(d+(e*f))
 Step 1: Reverse the infix string. Note that while reversing the string you
must interchange left and right parentheses.
 Step 2: Obtain the postfix expression of the expression obtained from Step
1.
 Step 3: Reverse the postfix expression to get the prefix expression
This is how you convert manually for theory question in the exam
1.
1. String after reversal – ))f*e(+d(-)c+)b/a((
2. String after interchanging right and left parenthesis – ((f*e)+d)-(c+
(b/a))
3. Apply postfix – Below is postfix (On this page you check infix to
postfix conversion rule)
4. Reverse Postfix Expression (Given After the image below)

Sr. No. Expression Stack Prefix

0 ( (

1 ( ((

2 f (( f

3 * ((* f

4 e ((* fe

5 ) ( fe*

6 + (+ fe*
Sr. No. Expression Stack Prefix

7 d (+ fe*d

8 ) fe*d+

9 – – fe*d+

10 ( -( fe*d+

11 c -( fe*d+c

12 + -(+ fe*d+c

13 ( -(+( fe*d+c

14 b -(+( fe*d+cb

15 / -(+(/ fe*d+cb

16 a -(+(/ fe*d+cba

17 ) -(+ fe*d+cba/

18 ) – fe*d+cba/+

19 fe*d+cba/+-

Final prefix: -+/abc+d*ef

You might also like