Home Contact About

Operators precedence and associativity are essential concepts in C programming language that govern
how expressions involving multiple operators are evaluated. The order of operations is important in
ensuring that expressions are evaluated correctly and consistently. In this article, we will provide
a detailed explanation of operators precedence and associativity in C, including their definition,
concepts, rules, examples, and real-life use cases.

Operators precedence refers to the order in which the different operators in an expression are
evaluated. C defines a set of rules that specify the precedence of each operator in an expression.
For example, multiplication and division have a higher precedence than addition and subtraction,
so they are evaluated before the addition and subtraction operations. Parentheses can be used to
override the default precedence and force certain operations to be evaluated first.

Associativity, on the other hand, refers to the order in which operators with the same precedence
are evaluated. C defines left-to-right associativity for most operators, which means that
expressions with the same precedence are evaluated from left to right. However, there are
some operators such as assignment operators that have right-to-left associativity, meaning
that expressions with the same precedence are evaluated from right to left.

The following table shows the operators precedence in C, from highest to lowest:

Operators Associativity
() [] -> . Left to right
! ~ ++ -- + - * & sizeof Right to left
* / % Left to right
+- Left to right
<< >> Left to right
< <= > >= Left to right
== != Letf to Right
& Left to right
^ Left to right
| Left to right
&& Left to right
|| Left to right
?: Right to left
= += -= *= /= %= <<= >>= &= ^= |= Right to Left
, Right to Left

It is important to note that expressions within parentheses are always evaluated first,
regardless of their precedence or associativity. For example, in the expression '5 * (3 + 2)',
the parentheses force the addition operation to be evaluated first, resulting in the value
of 5 being multiplied by 5 instead of 3.

In addition, C allows the use of parentheses to override the default precedence and
associativity of operators. For example, in the expression '5 + 3 * 2', the
multiplication operation has a higher precedence than the addition operation, so it
would normally be evaluated first. However, we can use parentheses to change the order
of evaluation: '(5 + 3) * 2'.

Operators precedence and associativity are important concepts to understand when working
with complex expressions in C. By following the rules and guidelines set by C, developers
can ensure that their code is evaluated correctly and consistently.