Operator Precedence and Associativity in C

Learn via video course
FREE
View all courses
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
Topics Covered

Overview

The article "Operator Precedence and Associativity in C" delves into the fundamental concepts that govern the sequence and direction of operations in C programming. In C, understanding operator precedence and associativity is paramount for writing code that produces the expected results. This article provides a comprehensive exploration of these essential topics, ensuring that readers can harness the full power of operators in their C programs.

Operator Precedence and Associativity Table

Operators in the C programming language have varying levels of precedence and associativity, which dictate the order in which they are evaluated within expressions. This table provides a comprehensive reference for understanding the precedence and associativity of different operators in C:

PrecedenceCategoryOperatorLeft to Right Associativity
1Postfix increment++Yes
Postfix decrement--Yes
Expression of function()Yes
Expression of array[]Yes
Direct selection of member.Yes
Indirect selection of member->Yes
2Prefix increment++No
Prefix decrement--No
Cast(type)No
Unary plus or minus+ -No
Logical NOT!No
Bitwise NOT~No
Dereferece*No
Address of&No
Size ofsizeofNo
3Multiply, divide, or remainder* / %Yes
4Add or subtract+ -Yes
5Bitwise left shift<<Yes
Bitwise right shift>>Yes
6Relational operator <<Yes
Relational operator <=<=Yes
Relational operator >>Yes
Relational operator >=>=Yes
7Relational operator ====Yes
Relational operator !=!=Yes
8Bitwise AND&Yes
9Bitwise XOR^Yes
10Bitwise OR|Yes
11Logical AND&&Yes
12Logical OR
13Ternary conditional?:No
14Assignment=No
Addition or subtraction assignment+= -=No
Multiplication or division assignment*= /=No
Modulus assignment%=No
Bitwise AND assignment&=No
Bitwise exclusive OR and inclusive OR assignment^==
Bitwise left shift assignment<<=No
Bitwise right shift assignment>>=No
15Comma,Yes

This table serves as a valuable resource for programmers to accurately predict how expressions with multiple operators will be evaluated in C, ensuring code correctness and precision.

Operator Precedence in C

Operator precedence in C refers to the rules that determine the order in which operators are evaluated within an expression. This order of evaluation is crucial because it can significantly impact the outcome of an expression. C operators have different levels of precedence, with some operators having higher precedence than others. When multiple operators are present in an expression, those with higher precedence are evaluated first.

Understanding operator precedence is essential for writing correct and predictable C code. It ensures that expressions are evaluated in the intended order and helps avoid common programming errors.

Example of Operator Precedence in C

Let's explore an example to illustrate how operator precedence affects the evaluation of expressions in C:

Example 1:

In this example, we have an expression that involves addition and multiplication. The operator * (multiplication) has higher precedence than + (addition) in C. Therefore, according to operator precedence rules, the multiplication operation will be evaluated before addition.

Here's the step-by-step evaluation:

  1. Evaluate 3 * 2, which results in 6.
  2. Add 5 to the result of the multiplication, giving us 5 + 6.
  3. Finally, the addition is performed, and the result variable will be assigned the value 11.

So, result will be equal to 11. This example demonstrates how operator precedence ensures that the multiplication operation takes precedence over addition.

Understanding the precedence of operators is essential for writing correct and efficient C code, as it helps in controlling the order of operations in complex expressions.

What is Operator Associativity in C?

Let us say we want to calculate 12/3*2 using the C language. From the precedence and associativity table given below, we can see that the division and multiplication operators have the same precedence. So, why the compiler does not get confused about what to calculate first? Division or multiplication? This confusion is avoided using the associativity of operators.
When two operators have the same precedence, their associativity comes into play. Because division and multiplication operators have associativity (left to right), the operator written on the left gets evaluated first. Hence, in the above example, division is done before multiplication.

Associativity of operators is used to determine the direction (left-to-right or right-to-left) in which an expression will be evaluated. Associativity is only useful if two operators in an expression have the same precedence.

Examples of Operator Associativity in C

Example 1:

Example of Operator Associativity Since multiplication has the highest precedence, the multiplication operation will be performed first. Addition and subtraction operators have the same precedence, but because their associativity is left to right, the addition operation will be performed first, followed by subtraction.

The above expression will yield 12 as its value.

Example 2:

Example 2 of Operator Associativity The operators == and != have the same precedence. Because their associativity is left to right, the == operation was performed first, which yielded 0 as its output. Then, the != operation was performed between 0 and 5. So, the final output that we got was 1.

Example 3:

Output:

Let us first simplify the given expression by evaluating the parenthesis: ++a * 11 % 35 - 28 / 7. As the value of a is 5, the value of ++a in the given expression will become 6. Now, the multiplication and the remainder operators have equal precedence with a left to right associativity (refer to the table below). So, multiplication will be done first (6 * 11 = 66), followed by the remainder operation (66 % 35 = 31). After these two calculations, the expression simplifies to: 31 - 28 / 7. As division has higher precedence than subtraction, division will be done before subtraction. So, the final answer we get is 31 - 4 = 27.

Example of Operator Precedence and Associativity

Consider the following C expression:

In this expression, we have multiple operators, including subtraction -, addition +, multiplication *, and division /. To understand how operator precedence and associativity work, let's break down the evaluation step by step:

  1. Operator Precedence: According to C's operator precedence rules, multiplication * and division / have higher precedence than addition + and subtraction -. Therefore, these multiplicative operations are evaluated before the additive operations.

    So, the expression is effectively grouped as:

  2. Operator Associativity: When operators have the same precedence, associativity determines the order of evaluation. In C, most binary operators, including -, +, *, and /, have left-to-right associativity. This means they are evaluated from left to right within the same precedence level.

    With left-to-right associativity, the expression is evaluated as follows:

    • 10 - 2 is evaluated first, resulting in 8.
    • 3 * 5 is evaluated next, resulting in 15.
    • 15 / 2 is evaluated last, resulting in 7 (integer division, discarding the remainder).

Important Points

  1. Operator Precedence: Operator precedence in C determines the order in which different operators are evaluated in an expression. Operators with higher precedence are evaluated first, followed by operators with lower precedence.

  2. Operator Associativity: When two or more operators have the same precedence in an expression, operator associativity determines the order of evaluation. Most binary operators in C have left-to-right associativity, meaning they are evaluated from left to right within the same precedence level.

  3. Parentheses Override Precedence: You can use parentheses ( ) to override the default precedence and force a specific sub-expression to be evaluated first. Expressions within parentheses are always evaluated before other parts of the expression.

  4. Unary Operators: Unary operators like increment ++ and decrement -- have higher precedence than most binary operators. Be aware of their behavior, especially when they are used as prefix or postfix operators.

  5. Chaining Operators: Chaining comparison operators (e.g., a > b > c) is not possible in C due to operator associativity. Each comparison should be evaluated separately.

  6. Assignment Operators: Assignment operators have lower precedence than most arithmetic and relational operators. Be cautious when mixing assignment operators with other operators in expressions.

Conclusion

  • Operator Precedence and Associativity are foundational in C programming. Grasping these ensures that the code behaves predictably, emphasizing their significance in writing effective C programs.
  • The provided table of operator precedence and associativity is a valuable tool. Programmers should familiarize themselves with it to avoid common mistakes and ensure that complex expressions evaluate correctly.
  • Parentheses ( ) are a powerful tool in C, allowing developers to override the default order of operations, ensuring clarity and precision in expressions.
  • Being aware of unary operators, especially their higher precedence, is key to understanding how expressions will evaluate, particularly when they're used in both prefix and postfix forms.
  • In C, chaining comparison operators isn't directly feasible due to operator associativity, underlining the importance of evaluating each comparison separately.