Precedence of Operators in C Tutorial

“Winning takes precedence over all. There’s no gray area. No almost.” Kobe Bryant

Before reading this section we’re assuming you are familiar with arithmetic operators.

Let’s say we have a variable named x and the value that we want to assign to this variable is the result of an expression which is 2+3*4/2.

What’s the final value assigned to the x variable?

Do you think it is 10? Is it 8?

This is where precedence comes in.

Based on precedence rules, arithmetic operators have different priority.

For example the multiplication * operator has higher priority than addition + operator and so if you saw an expression like 2+3*6 the result will be 20. This means in the expression before, first the two values 3 and 6 will be multiplied together and the result is added to the value 2.

In the list below you can see operators in order of decreasing precedence:

Operators Associativity
() Left to Right
* / Left to Right
+ – Left to Right
= Right to Left

As the table above shows, parentheses has the highest precedence and next is multiplication& division and after that is addition& subtraction and at the end we have assign operator.

For example if we had an expression like this:

int x = (30 + 20) * 10;

First the result in the parentheses should be declared (which will be 50) and then the result is multiplied by 10 (so the final result is 500) and at the end this result is assigned to the variable x.

Note: Associativity declares the order of operand execution.

For example the associativity in multiplication operator is from Left to Right. This means if we have an expression like (2+3)*4, the left operand executes first and then the right operand. So the result is:

5*4 = 20.

Example:

#include <stdio.h>

int
main() {

int a = 10 ;
int b = 20;
int c = 30 ;
int d = 40;

int result = (a+b) * d; // (10+20) * 40
printf("The result is: %dn", result);

result = ((a+b) /2) * c; // ((10+20)/2) * 30
printf("The result is: %dn", result);

result = c+d/10 * d; // 30+((40/10) * 40)
printf("The result is: %dn", result);

return 0;
}

Output:

The result is: 1200

The result is: 450

The result is: 190