• Home
  • 3.25 Operator Associativity

3.25 Operator Associativity

View Categories

3.25 Operator Associativity

1 min read

Operator associativity determines the direction in which operators with the same precedence are grouped in an expression. Most binary operators associate from left to right, while unary, conditional, and assignment operators generally associate from right to left.

#include <stdio.h>

int main()
{
    int result;

    result = 20 / 5 * 2;

    printf("result = %d\n", result);

    return 0;
}

Example Output #

result = 8

Explanation #

The / and * operators have the same precedence. Both associate from left to right, so the expression:

20 / 5 * 2

is grouped as:

(20 / 5) * 2

The result is therefore 8.

Assignment operators associate from right to left. For example:

int a, b, c;

a = b = c = 10;

is grouped as:

a = (b = (c = 10));

Operator Associativity Table #

Precedence Operators Associativity
1 () [] . -> Left-to-right
2 ++ -- + - ! ~ sizeof (type) Right-to-left
3 * / % Left-to-right
4 + - Left-to-right
5 << >> Left-to-right
6 < <= > >= Left-to-right
7 == != Left-to-right
8 & Left-to-right
9 ^ Left-to-right
10 | Left-to-right
11 && Left-to-right
12 || Left-to-right
13 ?: Right-to-left
14 = += -= *= /= %= <<= >>= &= ^= |= Right-to-left
15 , Left-to-right

Associativity is relevant only when operators have the same precedence. It does not override precedence.

For example:

a + b * c

is grouped according to precedence as:

a + (b * c)

The associativity of + does not cause (a + b) * c, because * has higher precedence.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *