C Operator precedence and associativity Tutorial

In this section, we will learn what the operator precedence is and how to use it in C.

Note: Before reading this section, we’re assuming you are familiar with the `arithmetic` operators.

What is Operator Precedence in C?

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 like `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 the precedence rules, arithmetic operators have different priorities.

For example, the multiplication `*` operator has a higher priority compared to the 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 will be added to the value 2.

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

Arithmetic Operators 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 the next is `multiplication& division` and after that is the `addition& subtraction` and at the end we have the `assignment` operator.

Example: Operator Precedence in C

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`.

What is associativity of Operators in C?

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 after that, comes the right-hand operand. So the result will be as:

5*4 = 20.

Example: Associativity of Operators in C

#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: %d\n", result);

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

    result = c+d/10 * d; // 30+((40/10) * 40)
    printf("The result is: %d\n", result);
    
    return 0;
}

Output:

The result is: 1200

The result is: 450

The result is: 190
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies