precedence - hpgDesigns/hpgdesigns-dev.io GitHub Wiki

In mathematics and programming, the precedence of an operator is the order in which the operator is evaluated in the presence of other operators. For example, in the expression `1 + 4 / 2

  • 3 * 4, division and multiplication have the highest precedence. Hence, they are performed first, from left to right, leaving 1 + 2
  • 12`, the sum of which is simply 15.

Using the more complicated set of operators available in C++ (and, by extension, in EDL), the following table (shamelessly stolen from cppreference.com) lists operators in the order they are evaluated:

Precedence Operator Description Associativity
1 :: Scope resolution Left-to-right
2 ++ -- Suffix/postfix increment and decrement
() Function call
[] Array subscripting
. Element selection by reference
−> Element selection through pointer
3 ++ -- Prefix increment and decrement Right-to-left
+ Unary plus and minus
! ~ Logical NOT and bitwise NOT
(type) Type cast
* Indirection (dereference)
& Address-of
sizeof Size-of
new, new[] Dynamic memory allocation
delete, delete[] Dynamic memory deallocation
4 .* ->* Pointer to member Left-to-right
5 * / % Multiplication, division, and remainder
6 + Addition and subtraction
7 << >> Bitwise left shift and right shift
8 < <= For relational operators < and ≤ respectively
> >= For relational operators > and ≥ respectively
9 == != For relational = and ≠ respectively
10 & Bitwise AND
11 ^ Bitwise XOR (exclusive or)
12 | Bitwise OR (inclusive or)
13 && Logical AND
14 Logical OR
15 ?: Ternary conditional Right-to-Left
16 = Direct assignment (provided by default for C++ classes)
+= −= Assignment by sum and difference
*= /= %= Assignment by product, quotient, and remainder
<<= >>= Assignment by bitwise left shift and right shift
&= ^= |= Assignment by bitwise AND, XOR, and OR
17 throw Throw operator (for exceptions)
18 , Comma Left-to-right

Hence, 1 == 2 << 3 + 4 * 5 is actually performed right to left, since the operators are of ascending precedence. Multiplication is performed first, then addition, then the left shift, then the comparison. Writing it as 5 * 4 + 3 << 2 == 1 does not change the order in which they are performed, but does change the result, as a << b is not the same as b << a. This is known as communativity.

⚠️ **GitHub.com Fallback** ⚠️