DEV Community

Charlie Barajas
Charlie Barajas

Posted on

Why Precedence Matters πŸ€“

Let's look at a simple example. What do you think the value of result would be here?

C++

int x = 5;
int y = 10;
int z = 2;
int result = x + y * z;
If you just go from left to right, you might think the calculation is 5 + 10 = 15, and then 15 * 2 = 30. But the correct answer is 25. Why? Because the multiplication operator (*) has higher precedence than the addition operator (+). So, the expression is evaluated as y * z first, which is 10 * 2 = 20, and then x + 20 is calculated, giving you 5 + 20 = 25.

A Simple Breakdown πŸ“‹
C++ has many operators, but some of the most common ones you'll encounter, from highest precedence to lowest, include:

Postfix operators (), [], ->, . (e.g., function calls, array access)

Unary operators ++, --, !, ~, * (dereference), & (address of)

Multiplicative operators *, /, %

Additive operators +, -

Shift operators <<, >>

Relational operators <, <=, >, >=

Equality operators ==, !=

Logical AND &&

Logical OR ||

Assignment operators =, +=, -=, *=, etc.

The Role of Associativity πŸ”„
What happens when you have two operators with the same precedence? This is where associativity comes in. It determines the direction of evaluation. For most binary operators, like addition and subtraction, the associativity is left-to-right. For example, in a - b + c, the expression is evaluated as (a - b) + c. However, some operators, like the assignment operators, have right-to-left associativity, so a = b = 5 is evaluated as a = (b = 5).

The Best Practice: Use Parentheses () πŸ“
While it's good to know the rules, relying on operator precedence can make your code harder to read and prone to subtle bugs. The simplest and most effective solution is to use parentheses () to explicitly control the order of evaluation.

Instead of x + y * z, write x + (y * z). This makes your intention crystal clear to anyone reading the code, including your future self! Parentheses can make your code more robust and much easier to maintain. They are your best friend when it comes to controlling operator precedence. Happy coding!

Provide an example of complex operator precedence.

Explain operator associativity in more detail.

What are some common pitfalls with operator precedence?

Top comments (0)