Variables, Types and Operators

How does operator precedence work in C++?

Can you clarify the rules around operator precedence in C++? How can I control the order of operations?

Abstract art representing computer programming

Operator precedence in C++ determines the order in which operators are evaluated in an expression when there are multiple operators. If operators have the same precedence, they are evaluated based on their associativity (left-to-right or right-to-left).

Here's a quick summary of the precedence and associativity of some common operators, from highest to lowest precedence:

  1. Postfix operators (e.g., ++-) - left to right
  2. Prefix operators (e.g., ++-!) - right to left
  3. Multiplicative operators (, /%) - left to right
  4. Additive operators (+, ) - left to right
  5. Relational operators (<<=>>=) - left to right
  6. Equality operators (==!=) - left to right
  7. Logical AND (&&) - left to right
  8. Logical OR (||) - left to right
  9. Assignment operators (=+==, etc.) - right to left

For example:

// a is 17, because * has
// higher precedence than +
int a = 5 + 3 * 4;

// b is true, because && has
// higher precedence than ||
bool b = true || false && false;

If you want to override the default precedence, you can use parentheses. Expressions inside parentheses are always evaluated first. For example:

// a is 32, because (5 + 3) is evaluated first
int a = (5 + 3) * 4;

// b is false, because (true || false)
// is evaluated first
bool b = (true || false) && false;

It's often a good idea to use parentheses even when they're not strictly necessary, as they can make your code more readable and less prone to errors.

Also, keep in mind that the precedence and associativity rules can interact in complex ways when there are many operators in a single expression. When in doubt, use parentheses to make your intent clear.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved