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

C++
#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.

Similar Reads

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....

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:...

Operator Precedence Table in C++

The operator precedence table in C++ is a table that lists the operators in order of their precedence level. Operators with higher precedence are evaluated before operators with lower precedence. This table also includes the associativity of the operators, which determines the order in which operators of the same precedence are processed....

Contact Us