Operator Associativity in C++
Operator associativity determines the order in which operands are grouped when multiple operators have the same precedence. There are two types of associativity:
Left-to-right associativity: In expressions like a + b – c, the addition and subtraction operators are evaluated from left to right. So, (a + b) – c is equivalent.
Right-to-left associativity: Some operators, like the assignment operator =, have right-to-left associativity. For example, a = b = 4; assigns the value of b to a.
For expression:
int x = 10 - 5 - 2;
As, subtraction is left-associative, that’s why 10 – 5 evaluated first, resulting in x = 3. But in case of multiplication:
int x = 2 * 3 * 4;
Now 3 * 4 is evaluated first, resulting in x = 24 because multiplication is right-associative.
Example of C++ Operator Associativity
#include <iostream>
using namespace std;
int main()
{
// Subtraction is left-associative
int result = 10 - 5 - 2;
cout << "Result: " << result << endl; // Output: 3
// Multiplication is right-associative
result = 2 * 3 * 4;
cout << "Result: " << result << endl; // Output: 24
return 0;
}
// This code is contributed by Susobhan Akhuli
Output
Result: 3 Result: 24
Understanding both the precedence and associativity of operators is crucial for writing expressions that produce the desired results.
Operator Precedence and Associativity in C++
In C++,operator precedence and associativity are important concepts that determine the order in which operators are evaluated in an expression. Operator precedence tells the priority of operators, while associativity determines the order of evaluation when multiple operators of the same precedence level are present.
Contact Us