Operator precedence and associativity

Operator Precedence - Like a Recipe Order

Imagine you're following a recipe to make a sandwich. The recipe tells you to first spread the butter, then add the cheese, and finally put on the lettuce. In C language, operators also have a sequence they follow when combining different operations. This sequence is called operator precedence.

Operator Associativity - Like Passing Ingredients:

Now, think about making a sandwich with layers. You start with the bread, then add the ingredients one by one. Operator associativity in C is a bit like the direction you pass ingredients. Some operations go from left to right, and some go from right to left.

Operator Precedence:

Operator precedence is like the order of operations in math. Some operators have higher precedence, meaning they get executed first, just like in a recipe where you do certain steps before others.

int result = 2 + 3 * 4;

In this case, multiplication has higher precedence than addition. So, it's like saying 2 + (3 * 4), and the result is 14.


Operator Associativity:

Operator associativity decides the order when operators of the same precedence appear together. It's like saying if you should add ingredients from the left first or from the right first.

int result = 10 / 2 * 3;

Division and multiplication have the same precedence. In this case, they follow left-to-right associativity. So, it's like saying ((10 / 2) * 3), and the result is 15.


In a simple way

Precedence: Some operators go first, just like steps in a recipe.

Associativity: When operators have the same precedence, it's like passing ingredients in a specific order.


Post a Comment

0 Comments