Code Skiller logoCB Logo
Logo LearnLearnLogo PracticePracticeLogo HireHireLogo IDEIDE

Operator Precedence & Associativity

User image

Published by

sanya sanya

Published at: 27th Jul, 2023
1.64 mins read

What is Precedence?

Operator precedence refers to the rules that determine the order in which operators are evaluated in an expression. It defines the hierarchy of operators based on their priority levels. Operators with higher precedence are evaluated first.

For example, in the expression ‘2 + 3 * 4’, the multiplication operator (‘*’) has higher precedence than the addition operator (‘+’). So, according to operator precedence, the multiplication will be performed first, resulting in ‘2 + (3 * 4) = 2 + 12 = 14’.

What is Associativity?

Associativity is a property of operators that determines the order in which operators of the same precedence are evaluated. It specifies whether operators are evaluated from left to right (left associativity) or from right to left (right associativity).

For example, in the expression ‘6 - 3 - 1’, both subtraction operators (‘-’) have the same precedence. However, the operators are left associative, so the expression is evaluated as ‘(6 - 3) - 1 = 3 - 1 = 2’.

When do they matter?

Operator precedence and associativity matter when an expression contains multiple operators of different precedence levels. They ensure that the expression is evaluated correctly according to the rules of the programming language.

It is important to understand operator precedence and associativity to avoid unintended errors and to write expressions that produce the desired results.

Table

https://images.codingblocks.com/dsa/operator%20prec.png? oops,Learn free Java tutorials,C tutorials,C++ tutorials,C/C++ Graphics  tutorials,HTML: C++ expression and operator precedence and associativity oops,Learn free Java tutorials,C tutorials,C++ tutorials,C/C++ Graphics  tutorials,HTML: C++ expression and operator precedence and associativity

Examples with codes

Example 1: Operator Precedence

#include

using namespace std;

int main() {

int result = 2 + 3 * 4;

cout << result << endl; // Output: 14

return 0;

}

Example 2: Associativity

#include

using namespace std;

int main() {

int result = 6 - 3 - 1;

cout << result << endl; // Output: 2

return 0;

}

Library

WEB DEVELOPMENT

FAANG QUESTIONS