What is the precedence and associativity of operators in C++?
Who defines operator precedence and associativity, and how does it relate to order of evaluation? explains how those properties emerge from the grammar. However, I am simply interested in a list of all the rules.
This question is supposed to be a community FAQ which can be referenced instead of the cppreference article.
C++ Operator Precedence
and Arity
0,id,this,[]{},(expression),(x, ...),requires () {}::::is also not an operator strictly speaking, but a way of combining multiple identifiers into a single name.Binary
x++x--type()type{}x()x[].,->static_casttypeid, ...static_castare also classified as a postfix expression, although usually people don't consider it an operator and there is usually no confusion as to its precedence.Various
++x,--x+x-x!x~x(type) x*x&xsizeofco_awaitnewdeleteco_await,new, anddelete, which not everyone expects to be an operator.Note that the operand to
sizeofcannot be a C-style cast, e.g.sizeof (int)xis parsed assizeof(int)followed byx.Various
.*->*Binary
*/%+-<<>><=><><=>=a < b < cmeans(a < b) < cand is likely a mistake.==!=a == b == cmeans(a == b) == cand is likely a mistake.&^|&&||a?b:cbis parsed as if it was parenthesized, so its precedence doesn't matter.Ternary
=+=...co_yieldthrowVarious
,Binary
Note that this list equally applies to operator precedence in C. The C++ rules are a superset of the C rules, meaning that they are the same, just with more operators.
Common Examples
x + y * zx + (y * z)*has higher precedencex + y + z(x + y) + z+is left-associativex = y = zx = (y = z)=is right-associativex || y && zx || (y && z)&&has higher precedence(this makes disjunctive normal forms
easy to write)
x || y || z(x || y) || z||is left-associativex = y ? a : bx = (y ? a : b)?:has higher precedence,and is right-associative
*x++*(x++)*++x*(++x)x | y << zx | (y << z)<<has higher precedencecout << x ? y : z(cout << x) ? y : z<<has higher precedencex << y + zx << (y + z)+has higher precedenceSee also on other sites