Operator Precedence and Associativity in C

Updated on July 23, 2024

Article Outline

In C programming, the operator precedence determines the order or the priority of the operators when multiple operators are in their expression. We call these operators symbols that tell the compiler to perform specific mathematical, logical, or relational operations. When an expression contains multiple operators, the compiler must decide the order in which to apply them, ultimately maintaining the ambiguity of the expression and avoiding the use of parenthesis. The decision to solve the expression is governed by two key rules: operator precedence and associativity.

 

In this article, we will go through the operator precedence and associativity in C through which we decide the priority of operators. We’ll see the associativity order of left-to-right and right-to-left. Along with this, we will explore the in-depth explanations, examples, and the operator precedence and associativity table for more information. Let’s get started.

Operator Precedence in C

Operator precedence refers to the rules in C that determine the order in which the different operators are evaluated in an expression. The rule of operator precedence states that operators possessing higher priority levels should be evaluated ahead of those with lower priorities.

 

Understanding the operator precedence is crucial in C programming, as it plays a significant role in ensuring the proper evaluation of an expression. When dealing with multiple operators within an expression, this rule guides us in identifying the primary operator that needs to be evaluated first.

 

Let’s understand the operator precedence of an expression in C language with the help of an example. We will now evaluate the following expression using the operator precedence:

 

Expression:

int answer = 10  + 4 * 5;

In this example, we have an expression that involves multiplication and addition operations. As per the operator precedence table, the multiplication operator (*) will have a higher precedence than (+) addition. Therefore, as the precedence, 4 * 5 will be evaluated first, resulting in 20, and then 10 + 20 is evaluated to get the final answer as 30.

 

But now, if you use the parenthesis, the order of precedence and the expression answer will be changed. Let’s see how.

int answer = (10  + 4) * 5;

Here, as per the operator precedence table, the parenthesis operator () will have higher precedence than the multiplication (*) operator and, finally, the (+) addition operator. Therefore, the precedence of 10 + 4 will be evaluated first to give the result of 14. Then 14 * 5 is evaluated to get the final result as 70.

 

We have now learned the concept of how operator precedence ensures that the multiplication operation takes precedence over addition. Let’s now see the expression evaluation using operator precedence in C.

 

Code Example 1: Using operator precedence to solve an expression in C.

#include <stdio.h>  int main() {  int n1, n2; printf("Enter two numbers to evaluate the expression -> (n1 + n2) * 5:n"); scanf("%d %d", &n1, &n2);  // Evaluate an example expression with the two numbers int answer = (n1 + n2) * 5;  printf("Result of the expression (n1 + n2) * 5: %dn", answer);  return 0; }

Output:

Enter two numbers to evaluate the expression -> (n1 + n2) * 5: 34 3 Result of the expression (n1 + n2) * 5: 185

Explanation:

 

In this example, we evaluate the expression (n1 + n2) * 5 using operator precedence. Here,

 

  • We have declared two variables n1 and n2, and asked the user to input two numbers to evaluate in the expression (n1 + n2) * 5.
  • The expression (n1 + n2) * 5 is evaluated using the operator precedence.
  • The expression inside the parentheses (n1 + n2) is evaluated first because parentheses have the highest precedence.
  • Now, the result of the parentheses (5 in this case) is multiplied by 5.
  • Finally, the answer is stored in the variable “answer”.

 

Code Example 2: Using operator precedence to solve an expression of relational operators in C.

#include <stdio.h>  int main() {  int n1, n2; printf("Enter two numbers to evaluate the expressions:n"); scanf("%d %d", &n1, &n2);  int ans1 = n1 < n2; printf("Result of the expression n1 < n2 = %dn", ans1); // relational operator of Less than int ans2 = n1 <= n2; printf("Result of the expression n1 <= n2 = %dn", ans2); // relational operator of Less than or equal to int ans3 = n1 > n2; printf("Result of the expression n1 > n2 = %dn", ans3); // relational operator of Greater than int ans4 = n1 >= n2; printf("Result of the expression n1 >= n2 = %dn", ans4); // relational operator of Greater than or equal to return 0; }

Output:

Enter two numbers to evaluate the expressions: 323 54  Result of the expression n1 < n2 = 0 Result of the expression n1 <= n2 = 0 Result of the expression n1 > n2 = 1 Result of the expression n1 >= n2 = 1

Explanation:

In this example, we evaluate the expression of relational operators with operator precedence. Here,

  • We have declared two variables, n1 and n2 and asked the user to input two numbers to evaluate the expression of relational operators (<, <=, >, >=).
  • We will first evaluate the expression using the condition: n1 is less than n2 (n1 < n2). Here, the input is 323 and 54 for n1 and n2, respectively. After evaluating the condition, if the result of the condition is true, the ans1 will be 1. Otherwise, it’s 0. In our case, the ans1 is 0.
  • Next, we evaluate the expression using the condition: n1 is less than or equal to n2 (n1 <= n2). Here, the input is 323 and 54 for n1 and n2 respectively. After evaluating the condition, if the result of the condition is true, the ans2 will be 1, otherwise it’s 0. In our case, the ans2 is 0 as n1 is not less or equal to n2.
  • We will evaluate the expression using the condition: n1 is greater than n2 (n1 > n2). Here, the input is 323 and 54 for n1 and n2 respectively. After evaluating the condition, if the result of the condition is true, the ans3 will be 1, otherwise it’s 0. In our case, the ans3 is 1 as n1 is greater than n2.
  • We will evaluate the expression using the condition: n1 is greater than or equal to n2 (n1 >= n2). Here, the input is 323 and 54 for n1 and n2 respectively. After evaluating the condition, if the result of the condition is true, the ans4 will be 1, otherwise it’s 0. In our case, the ans4 is 1 as n1 is greater than n2 but not equal.
*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Operator Associativity in C

The operator associativity in C is used when there exist two operators of the same precedence in an expression. The operator associativity in C can be either Left to Right or Right to Left. Associativity means the way operators are handled in an expression when two operators with the same precedence appear. For example, let’s say we have an expression: 8 / 4 * 5. Here, the expression has both operators of the same precedence, that is, division and multiplication. Therefore, we will use the operator associativity in C to evaluate the expression for finding the correct result.

 

We will now evaluate the following expression using the operator associativity:

 

Expression:

int answer = 8 / 4 * 5

Here, the multiplication and division operator has the same operator precedence. Therefore, we will use the operator associativity to evaluate this expression. The associativity of multiplication and division is from Left to Right. Therefore, 8 / 4 is evaluated first, resulting in 2, and then 2 * 5 is evaluated to give 10.

 

So, associativity is only useful when two operators in an expression have the same precedence.

 

Code Example:

#include <stdio.h> int main() { int a = 8; int b = 4; int c = 5; int answer = a / b * c; printf("The result of the evaluated expression a / b * c is: %dn", answer); return 0; }

Output:

The result of the evaluated expression a / b * c is: 10

Explanation:

In this example, we are evaluating the expression a / b * c using the operator associativity. Here, as both division and multiplication operators have the same precedence, therefore the order of associativity will be used. The order of associativity of both operators is from Left to Right. After the evaluation is done, the result becomes 10 after all operations.

Operator Precedence and Operator Associativity Table in C

The given table represents the operator precedence from highest to lowest and their associativity in C language:

Precedence Operators Description Associativity
1 ()
[]
->
.
Parentheses
Square brackets
Structure pointer
Dot operator
Left to Right
2 !
~
++
–-
+

*
&
sizeOf
(type)
Logical NOT
Bitwise complement
Increment
Decrement
Unary plus
Unary minus
Dereference operator
AddressOf operator
Size in bytes
Cast operator
3 *
/
%
Multiplication
Division
Modulus
Left to Right
4 #ERROR! Addition
Subtraction
Left to Right
5 <<
>>
Bitwise shift left
Bitwise shift right
Left to Right
6 <
<=
>
>=
Relational less than
Relational less than or equal
Relational greater than
Relational greater than or equal
Left to Right
7 #ERROR! Relational is equal to
Relational is not equal to
Left to Right
8 & Bitwise AND Left to Right
9 ^ Bitwise exclusive OR Left to Right
10 | Bitwise inclusive OR Left to Right
11 && Logical AND Left to Right
12 || Logical OR Left to Right
13 ?: Ternay conditional Right to Left
14 #ERROR! Assignment
Addition assignment
Subtraction assignment
Multiplication assignment
Division assignment
Modulus assignment
Bitwise shift left assignment
Bitwise shift right assignment
Bitwise AND assignment
Bitwise exclusive assignment
Right to Left
15 , Comma operator Left to Right

Example of Operator Precedence and Associativity

We will now see a detailed and comprehensive example of operator precedence and associativity in an expression in C. Consider the following expression:

int res = 30 - 3 + 4 * 7 / 3

In the given expression, we have used the different operators in an expression including multiplication, division, subtraction, and addition. As we can see in the expression, division and multiplication have higher precedence or priority compared to addition and subtraction. Let’s now understand this example expression in more detail:

 

  • The associativity of operators of the same precedence level (multiplication/division and addition/subtraction) is evaluated from left to right.
  • In expressions involving multiple operators of different precedence levels, adding parentheses can clarify the order of evaluation and avoid ambiguity.

 

Therefore, after adding the parenthesis, the expression becomes:

int res = (30 - 3) + (4 * 7) / 3

As per the rules of associativity, the expression will be evaluated as:

  • First, (30 – 3) ensures that subtraction is evaluated first, resulting in 27.
  • Then, (4 * 7) ensures that multiplication is evaluated next, resulting in 28.
  • Next, the division is done 28 / 3, which results in 9.
  • Finally, (27 + 9) gives us the answer of 36.

 

Example:

#include <stdio.h>  int main() {  int a = 30; int b = 3; int c = 4; int d = 7;  int ans = (a - b) + (c * d) / b;  printf("The result of the evaluated expression (a - b) + (c * d) / b is: %dn", ans);  return 0; }

Output:

The result of the evaluated expression is: 36

Common Pitfalls

1. Misunderstanding Parenthesis

The most common pitfall in expression evaluation is the misunderstanding of the logical and relational operator’s precedences. It must be used carefully. Let’s understand this with an example:

int x = 10, y = 15, c = 20; if (x < y && y < z) printf("Output is: n");

In this example, the relational operators (<) have higher precedence than the logical AND (&&), so x < y and y < z are evaluated first before the logical AND operation.

 

2. Incorrect usage of associativity

 

When working with operators like conditional and assignment, the associativity is assumed incorrectly. Let’s see how:

int x, y, z;   X = y = z = 20;

In this example, as the assignment operators have right-to-left associativity, 20 is assigned to z first, followed by y receiving the value of z (20), and x receiving the value of y (20).

 

3. Relying just on operator precedence without considering the associativity.

 

4. Misuse of similar symbols and different operators.

Important Points

While working with the expressions in the C program, you must be aware of the operator precedence and their associativity. But there are some important points that everyone must remember while working with this:

 

  • Operators in C have different levels of precedence. Where the operators with the higher precedence are evaluated first, followed by the lower precedence operators.
  • The associativity will only work when there exist two operators of the same precedence. If no two operators of the same precedence aren’t there, associativity doesn’t exist.
  • Parentheses() can be used to cause a specified sub-expression to be evaluated first, overriding the default precedence. Parenthetically enclosed expressions are always evaluated before their component components.
  • Use parentheses liberally in complex expressions to enhance readability.
  • In the operator precedence, the postfix ++ has a higher precedence than the prefix ++, and their associativity differs as well. Prefix ++ has right-to-left associativity, while postfix ++ has left-to-right associativity.
  • A comma must be used carefully as it has the lowest level of precedence among all the operators in an expression.
  • Because of operator associativity, chaining comparison operators (such as x > y > z) is not feasible in C language. Every comparison needs to be assessed independently.

Conclusion

In conclusion, operator precedence and associativity are the core elements in C programming. It’s about getting the order right when it comes to operators within expressions: a key task if you want to write code that does what you intend it to do and does it efficiently without any bugs. This article delves into some important points regarding this topic. Mastering the concept of operator precedence will empower programmers to produce not just any code but clear, efficient, and maintainable one – be it while dealing with simple arithmetic or complex algorithms. Always bear in mind that applying these rules guarantees that expressions are evaluated as expected.

 

This, in turn, adds up towards ensuring the reliability and correctness of C programs down the road for you as a developer gaining more experience – having an understanding of this would be helpful along your journey as a proficient C programmer.

 

FAQs
Operator precedence in C refers to the order in which the operators are evaluated in an expression. To ensure no ambiguity, operator precedence rules are used in the C programming language.
Expressions are evaluated without parenthesis only according to operator precedence and associativity principles. If the planned order of operations is different from the default regulations, this could result in unanticipated outcomes. In complex expressions or situations where precedence may not be immediately apparent, it is extremely crucial to utilise parentheses to indicate the order of actions.
Both multiplication and division have the same precedence in C. As they have the same precedence, we consider the associativity of operators, which will be right to left in this case.
Yes, the operator precedence in C can be changed using brackets or parenthesis.
Operator precedence by itself has little effect on a program's runtime efficiency. Nonetheless, utilising it correctly and comprehending it might result in more understandable and efficient code. Performance may be indirectly impacted by the misuse or misunderstanding of precedence, which can lead to logical fallacies or needless complexity.

Updated on July 23, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved