Thursday, 6 April 2023

Operators precedence and associativity in C

Operators in C have different levels of precedence, which determines the order in which they are evaluated in an expression. Operators with higher precedence are evaluated before operators with lower precedence.

Here is the precedence order of operators in C, from highest to lowest precedence:

  1. Parentheses ()
  2. Unary operators +, -, !, ~, ++, --, *, &, sizeof, _Alignof
  3. Multiplicative operators *, /, %
  4. Additive operators +, -
  5. Shift operators <<, >>
  6. Relational operators <, >, <=, >=
  7. Equality operators ==, !=
  8. Bitwise AND operator &
  9. Bitwise XOR operator ^
  10. Bitwise OR operator |
  11. Logical AND operator &&
  12. Logical OR operator ||
  13. Conditional operator ? :
  14. Assignment operators =, +=, -=, *=, /=, %=, <<=, >>=, &=, ^=, |=
  15. Comma operator ,

In addition to precedence, operators in C also have associativity, which determines the order in which operators with the same precedence are evaluated.

For example, the addition + and subtraction - operators have the same precedence, so they are evaluated from left to right, which means that expressions with + and - operators are evaluated from left to right.

Here's an example that shows both precedence and associativity:

int a = 5, b = 3, c = 2;
int result = a + b * c;

In this example, the multiplication * operator has higher precedence than the addition + operator, so it is evaluated first. Then, the addition + operator is evaluated to get the final result. The value of b is multiplied by c, which is 6, and then added to a, which is 5, to get the final result of 11.

It's important to understand the precedence and associativity of operators in C to correctly evaluate expressions and avoid errors in your code.

 

0 comments :

Post a Comment

Note: only a member of this blog may post a comment.

Machine Learning

More

Advertisement

Java Tutorial

More

UGC NET CS TUTORIAL

MFCS
COA
PL-CG
DBMS
OPERATING SYSTEM
SOFTWARE ENG
DSA
TOC-CD
ARTIFICIAL INT

C Programming

More

Python Tutorial

More

Data Structures

More

computer Organization

More
Top