Operator Precedence in C++
In C++, operator precedence specifies the order in which operations are performed within an expression. When an expression contains multiple operators, those with higher precedence are evaluated before those with lower precedence.
For expression:
int x = 5 - 17 * 6;
As, multiplication has higher precedence than subtraction, that’s why 17 * 6 is evaluated first, resulting in x = -97. If we want to evaluate 5 – 17 first, we can use parentheses:
int x = (5 - 17) * 6;
Now 5 – 17 is evaluated first, resulting in x = -72.
Example of C++ Operator Precedence
#include <iostream>
using namespace std;
int main()
{
// Multiplication has higher precedence
int result = 5 - 17 * 6;
cout << "Result: " << result << endl; // Output: -97
// Because of parentheses 5 - 17 will be calculated
// first
result = (5 - 17) * 6;
cout << "Result: " << result << endl; // Output: -72
return 0;
}
// This code is contributed by Susobhan Akhuli
Output
Result: -97 Result: -72
Remember that, using parentheses makes code more readable, especially when dealing with complex expressions.
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