Home C++ Tutorial C++ Operator Precedence

C++ Operator Precedence

by Team Impactmillions
7 minutes read

In this article, you’ll learn about what is Operator Precedence, Operator Precedence Table and more.

In C++, operator precedence dictates the order in which expressions containing multiple operators are evaluated. This is crucial for ensuring your code produces the intended results, especially when dealing with complex expressions.

What is Operator Precedence

Imagine you have a complex math problem with various operations like multiplication, addition, subtraction, and exponentiation. To solve it accurately, you follow the order of operations (PEMDAS: Parentheses, Exponents, Multiplication and Division (from left to right), Addition and Subtraction (from left to right)). Similarly, C++ has a set of rules that determine which operators are evaluated first in an expression.

For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.

Operator Precedence Table

C++ operators have different precedence levels, with higher precedence operators taking priority. Here’s a simplified table (consult your compiler’s documentation for the complete list):

1::Scope resolutionLeft-to-right →
2a++   a--Suffix/postfix increment and decrement
type()   type{}Functional cast
a()Function call
.   ->Member access
3++a   --aPrefix increment and decrementRight-to-left ←
+a   -aUnary plus and minus
!   ~Logical NOT and bitwise NOT
(type)C-style cast
*aIndirection (dereference)
sizeofSize-of[note 1]
co_awaitawait-expression (C++20)
new   new[]Dynamic memory allocation
delete   delete[]Dynamic memory deallocation
4.*   ->*Pointer-to-memberLeft-to-right →
5a*b   a/b   a%bMultiplication, division, and remainder
6a+b   a-bAddition and subtraction
7<<   >>Bitwise left shift and right shift
8<=>Three-way comparison operator (since C++20)
9<   <=   >   >=For relational operators < and ≤ and > and ≥ respectively
10==   !=For equality operators = and ≠ respectively
11a&bBitwise AND
12^Bitwise XOR (exclusive or)
13|Bitwise OR (inclusive or)
14&&Logical AND
15||Logical OR
16a?b:cTernary conditional[note 2]Right-to-left ←
throwthrow operator
co_yieldyield-expression (C++20)
=Direct assignment (provided by default for C++ classes)
+=   -=Compound assignment by sum and difference
*=   /=   %=Compound assignment by product, quotient, and remainder
<<=   >>=Compound assignment by bitwise left shift and right shift
&=   ^=   |=Compound assignment by bitwise AND, XOR, and OR
17,CommaLeft-to-right →

related posts

Leave a Comment