Conceptcore
Operator precedence
Also called operator precedence, precedence, order of operations, associativity, operator associativity, binding power, precedence climbing, Pratt parsing, operator-precedence parser, shunting yard, left-associative, right-associative, non-associative.
Operator precedence and associativity decide how a parser groups an expression without parentheses, such as 1 + 2 * 3. Languages agree on arithmetic but differ on bitwise and logical operators.
- Applies to
- core-languages
Idea
The text 1 + 2 * 3 has two possible trees: (1 + 2) * 3 is 9 and 1 + (2 * 3) is 7. A language picks one with two rules. Precedence says which operator binds more tightly: * binds more tightly than +, so the answer is 7. Associativity says how a chain of operators at the same level groups: - groups to the left, so 10 - 4 - 3 is (10 - 4) - 3, which is 3. Parentheses override both rules. Precedence is a rule of the grammar. It decides the shape of the abstract syntax tree, not the time at which each operand runs.
import re
# Binding power of each binary operator, and whether it groups to the right.
OPS = {"+": (10, False), "-": (10, False), "*": (20, False), "/": (20, False), "^": (30, True)}
def parse(tokens, min_bp=0):
"""Precedence climbing: read an operand, then take operators while they bind at least min_bp."""
left = tokens.pop(0)
if left == "(":
left = parse(tokens)
tokens.pop(0) # the closing ")"
while tokens and tokens[0] in OPS:
bp, right_assoc = OPS[tokens[0]]
if bp < min_bp:
break
op = tokens.pop(0)
right = parse(tokens, bp if right_assoc else bp + 1)
left = (op, left, right)
return left
def show(t):
return t if isinstance(t, str) else f"({show(t[1])} {t[0]} {show(t[2])})"
def value(t):
if isinstance(t, str):
return int(t)
a, b = value(t[1]), value(t[2])
return {"+": a + b, "-": a - b, "*": a * b, "/": a // b, "^": a**b}[t[0]]
for src in ["1 + 2 * 3", "(1 + 2) * 3", "10 - 4 - 3", "2 ^ 3 ^ 2", "8 / 4 / 2", "1 + 2 * 3 ^ 2 - 4"]:
tree = parse(re.findall(r"\d+|[-+*/^()]", src))
print(f"{src:<20} => {show(tree):<28} = {value(tree)}")
# If ^ grouped to the left, 2 ^ 3 ^ 2 would be (2 ^ 3) ^ 2 = 64.
OPS["^"] = (30, False)
print("left-grouping ^:", show(parse(re.findall(r"\d+|[-+*/^()]", "2 ^ 3 ^ 2"))))
1 + 2 * 3 => (1 + (2 * 3)) = 7
(1 + 2) * 3 => ((1 + 2) * 3) = 9
10 - 4 - 3 => ((10 - 4) - 3) = 3
2 ^ 3 ^ 2 => (2 ^ (3 ^ 2)) = 512
8 / 4 / 2 => ((8 / 4) / 2) = 1
1 + 2 * 3 ^ 2 - 4 => ((1 + (2 * (3 ^ 2))) - 4) = 15
left-grouping ^: ((2 ^ 3) ^ 2)
The parser gives each operator a binding power. After it reads an operand, it takes the next operator only if that operator binds at least as tightly as the current level, and it parses the right side at a higher level. For a left-associative operator, the right side starts one level higher, so an equal operator stops it. For a right-associative operator such as ^, the right side starts at the same level, so 2 ^ 3 ^ 2 is 2 ^ (3 ^ 2).
How it works
A table of levels. Each language documents a table of operators from the tightest to the loosest. Python's table lists the operators "from highest precedence (most binding) to lowest precedence (least binding)"1, and MDN says that "Operators with higher precedence become the operands of operators with lower precedence"2. Most languages put postfix operators and calls first, then unary operators, then multiplication, addition, shifts, comparisons, bitwise operators, logical operators, the conditional operator and assignment.
Associativity. Most binary operators group to the left, so 8 / 4 / 2 is 1. Assignment groups to the right, so a = b = 0 sets both. Exponentiation groups to the right in Python, JavaScript and mathematics: MDN gives 4 ** 3 ** 2 as 4 ** (3 ** 2)2. The conditional operator groups to the right in C-like languages, so a chain of ? : reads as an if-else chain. Some operators do not associate: Rust marks the comparison operators "Require parentheses", so a < b < c is a compile error6. Python gives the same text a third meaning: a < b < c is a chain that means a < b and b < c.
Unary operators. In Python, "The power operator binds more tightly than unary operators on its left; it binds less tightly than unary operators on its right"1, so -2 ** 2 is −4 and 2 ** -1 is 0.5. JavaScript does not choose: -2 ** 2 is a syntax error, and the program must write (-2) ** 2 or -(2 ** 2). In Rust, a method call binds more tightly than unary minus, so -2i32.pow(2) is −4.
Where languages differ. Languages agree on arithmetic but not on the other operators:
- Bitwise and comparison. In C, C++, Java, C# and JavaScript,
==binds more tightly than&, sox & 1 == 0meansx & (1 == 0). In Go,&is at the level of*, and Go has only "five precedence levels for binary operators"3, sox&1 == 0means(x & 1) == 0. Python and Rust also put&above==16. - Shift and addition. In C, Java and Rust,
1 << 2 + 1is1 << 3, which is 84. In Go,<<is at the level of*, so the same text is(1 << 2) + 1, which is 53. - Increment. In C,
*p++increments the pointer. In Go,++is a statement, so "statement *p++ is the same as (*p)++"3. - Null coalescing. C# puts
??below||, and the C# reference says that parentheses "change the order of evaluation imposed by operator precedence and associativity"5. JavaScript forbids??next to||or&&without parentheses. - Conditional and assignment. In C++, "the conditional operator has the same precedence as assignment operators", so
flag ? a : b = 9meansflag ? a : (b = 9); in C, the same text is an error7.
Grammar, not evaluation. The C and C++ standards have no precedence table: the levels "are derived from the grammar", and cppreference notes that "Precedence and associativity are compile-time concepts and are independent from order of evaluation"8. In f() + g() * h(), the multiplication groups first, but the language decides separately which call runs first. See order of evaluation.
Overloaded operators. An overloaded operator keeps the precedence of the built-in one. If a C++ library uses ^ for power, x ^ 3 * 2 still means x ^ (3 * 2), because ^ binds less tightly than *. C++ output with << keeps the precedence of the shift operator.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | TypeScript has the precedence table of JavaScript, including the syntax errors for -2 ** 2 and for ?? next to || without parentheses, but no example file exists. |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | Kotlin has a precedence table in its grammar, and all named infix functions share one level above the comparison operators, but no example file exists because kotlinc is not installed. |
| SQL | Native | SQL evaluates NOT before AND and AND before OR, and arithmetic before comparison, so a mix of AND and OR without parentheses can select rows that the author did not intend. |
| Bash | Native | Bash arithmetic in $(( )) uses the precedence of C, and between commands && and || have the same level and group to the left, but no example file exists. |
| PowerShell | Native | PowerShell documents a precedence table in about_Operator_Precedence, with comparison operators such as -eq below arithmetic, but no example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML has no operators. |
| CSS | Native | In calc(), multiplication and division bind more tightly than addition and subtraction, and parentheses group terms. |
| Regular expressions | Native | In a regular expression, repetition binds more tightly than concatenation, and concatenation binds more tightly than alternation, so ab|cd is (ab)|(cd). |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | precedence table; ** groups to the right; comparisons chain |
| JavaScript | native | precedence table; ** groups to the right; -2 ** 2 and a ?? b || c are syntax errors |
| TypeScript | native | as JavaScript |
| Java | native | the precedence of the C family; ?: and = group to the right |
| Kotlin | native | precedence table; named infix functions bind more tightly than comparisons |
| C# | native | the precedence of the C family; ?? and ?: group to the right |
| Go | native | five levels of binary operators; & and << at the level of * |
| Rust | native | precedence table; comparisons and ranges need parentheses |
| C | native | precedence derived from the grammar; == binds more tightly than & |
| C++ | native | as C; ?: at the level of assignment; overloaded operators keep their level |
| Bash | native | C precedence in $(( )); && and || of the same level between commands |
| PowerShell | native | precedence table; comparison operators such as -eq below arithmetic |
| SQL | native | NOT above AND above OR; arithmetic above comparison |
| Regex | native | repetition binds more tightly than concatenation, and concatenation more tightly than | |
| HTML | n/a | no operators |
| CSS | native | calc() with * and / above + and - |
Every general-purpose language in the table defines precedence and associativity, so the verdict is native. The arithmetic levels are the same everywhere, and the differences are in the bitwise operators, shifts, unary minus with exponentiation, comparisons and the null and conditional operators. Regular expressions and CSS calc() also have precedence, so their cells are native too.
The example files show the cases where languages differ. Python shows -2 ** 2 and a chained comparison. JavaScript shows the mixes that are syntax errors. Java shows that string concatenation groups to the left. C# shows ?? with +. Go shows its five levels, and Rust shows method calls, as and the ? operator. C shows x & 1 == 0 and *p++, with the warnings of the compiler, and C++ shows an overloaded ^ and the conditional operator with assignment.
import ast
# Unary minus binds less tightly than ** on its right, so -2 ** 2 is -(2 ** 2).
print(-2 ** 2, (-2) ** 2, 2 ** -1)
# Comparisons bind less tightly than bitwise operators, so this is (x & 1) == 0.
x = 6
print(x & 1 == 0)
# Comparisons chain: 1 < x < 10 means 1 < x and x < 10.
print(1 < x < 10, 1 < x > 5)
# `not` binds less tightly than ==, and `and` binds more tightly than `or`.
print(not 1 == 2, True or False and False)
# The conditional expression has almost the lowest precedence.
print(1 + 2 if x > 5 else 0)
# ast shows how the parser grouped an expression.
print(ast.dump(ast.parse("-2 ** 2", mode="eval").body))
t = ast.parse("a or b and c", mode="eval").body
print(type(t.op).__name__, [type(v).__name__ for v in t.values])
-4 4 0.5
True
True True
True True
3
UnaryOp(op=USub(), operand=BinOp(left=Constant(value=2), op=Pow(), right=Constant(value=2)))
Or ['Name', 'BoolOp']
- Verdict: native.
**binds more tightly than a unary minus on its left, so-2 ** 2is −4, and less tightly than one on its right, so2 ** -1is 0.5. Comparisons bind less tightly than&, sox & 1 == 0works as intended.1 < x < 10is a chain of two tests.notbinds less tightly than==, andandbinds more tightly thanor. Theastmodule shows the tree that the parser built.
#include <cmath>
#include <iostream>
// A type that uses ^ for power. The overloaded operator keeps the precedence of ^, which is below + and *.
struct Num {
double v;
};
Num operator^(Num a, int b) { return Num{std::pow(a.v, b)}; }
Num operator*(Num a, int b) { return Num{a.v * b}; }
int main() {
// << for output keeps the precedence of the shift operator: + binds more tightly, == less tightly.
std::cout << 1 + 2 << ' ' << (1 == 1) << '\n';
Num two{2};
std::cout << (two ^ 3 * 2).v << ' ' << ((two ^ 3) * 2).v << '\n';
// In C++, ?: and = have the same precedence and group to the right,
// so flag ? a : b = 9 means flag ? a : (b = 9). If it meant (flag ? a : b) = 9, a would become 9.
int a = 1, b = 2;
bool flag = true;
flag ? a : b = 9;
std::cout << a << ' ' << b << '\n';
// The comma operator has the lowest precedence of all.
int k = (a = 5, a + 1);
std::cout << k << '\n';
}
3 1
64 16
1 2
6
- Verdict: native. An overloaded operator keeps the level of the built-in one, so
two ^ 3 * 2istwo ^ (3 * 2), which is 64, not 16. Output with<<keeps the level of the shift operator. In C++,?:and=are at the same level and group to the right, soflag ? a : b = 9assigns tobonly whenflagis false, andastays 1. The comma operator has the lowest level of all.
public class Main {
public static void main(String[] args) {
// + groups to the left: number addition first, then string concatenation.
System.out.println(1 + 2 + "3");
System.out.println("1" + 2 + 3);
System.out.println("1" + (2 + 3));
// Shift binds less tightly than +, so this is 1 << 3.
System.out.println(1 << 2 + 1);
// == binds more tightly than &, so x & 1 == 0 would be x & (1 == 0), which does not compile for an int x.
int x = 6;
System.out.println((x & 1) == 0);
// The conditional operator groups to the right.
int n = 15;
String s = n % 15 == 0 ? "FizzBuzz" : n % 3 == 0 ? "Fizz" : n % 5 == 0 ? "Buzz" : String.valueOf(n);
System.out.println(s);
// Assignment groups to the right, and a compound assignment casts its result.
int a, b;
a = b = 7;
byte c = 10;
c += 300; // c = (byte) (c + 300)
System.out.println(a + " " + b + " " + c);
}
}
33
123
15
8
true
FizzBuzz
7 7 54
- Verdict: native.
+groups to the left, so the position of a string changes whether numbers are added or joined.+binds more tightly than<<.==binds more tightly than&, so the mask needs parentheses, and without them the code does not compile for anint. The conditional operator and assignment group to the right, and a compound assignment such asc += 300includes a cast to the type ofc.
#include <stdio.h>
int main(void) {
int x = 6;
/* == binds more tightly than &, so x & 1 == 0 means x & (1 == 0), which is always 0. */
printf("%d %d\n", x & 1 == 0, (x & 1) == 0);
/* + binds more tightly than <<. */
printf("%d\n", 1 << 2 + 1);
/* Postfix ++ binds more tightly than unary *, so *p++ reads *p and then moves p. */
int xs[] = {10, 20, 30};
int *p = xs;
int first = *p++;
printf("%d %d\n", first, *p);
(*p)++; /* parentheses increment the value instead */
printf("%d\n", xs[1]);
/* a < b < c is (a < b) < c, and a < b is 0 or 1. */
int a = 3, b = 2, c = 1;
printf("%d\n", a < b < c);
/* sizeof binds like a unary operator: sizeof x + 1 is (sizeof x) + 1. */
printf("%zu\n", sizeof x + 1);
/* The conditional operator groups to the right. */
int n = 10;
printf("%s\n", n % 15 == 0 ? "FizzBuzz" : n % 3 == 0 ? "Fizz" : n % 5 == 0 ? "Buzz" : "number");
return 0;
}
0 1
8
10 20
21
1
5
Buzz
- Verdict: native.
==binds more tightly than&, sox & 1 == 0isx & (1 == 0), which is 0 for everyx.+binds more tightly than<<. Postfix++binds more tightly than unary*, so*p++moves the pointer.a < b < ccompares 0 or 1 withc. Clang with-Wallwarns about all three of these mixes, and the program compiles with the warnings and prints the results.
// Shift binds less tightly than +, so this is 1 << 3.
Console.WriteLine(1 << 2 + 1);
// ?? binds less tightly than +, so this is have ?? (10 + 1).
int? have = 5;
Console.WriteLine(have ?? 10 + 1);
Console.WriteLine((have ?? 10) + 1);
// == binds more tightly than &, so x & 1 == 0 does not compile for an int x.
int x = 6;
Console.WriteLine((x & 1) == 0);
// A pattern after `is` uses its own `and`, `or` and `not`, with `not` binding most tightly.
object o = 7;
Console.WriteLine(o is int and > 0 and not 5);
// The conditional operator and ?? group to the right.
string? a = null, b = null, c = "c";
Console.WriteLine(a ?? b ?? c);
int n = 9;
Console.WriteLine(n % 15 == 0 ? "FizzBuzz" : n % 3 == 0 ? "Fizz" : n % 5 == 0 ? "Buzz" : n.ToString());
// Casts bind more tightly than binary operators.
double d = 7.9;
Console.WriteLine((int)d * 2 + " " + (int)(d * 2));
8
5
6
True
True
c
Fizz
14 15
- Verdict: native.
+binds more tightly than<<and??, sohave ?? 10 + 1ishave ?? (10 + 1).==binds more tightly than&. Patterns afterishave their ownand,orandnot.??and?:group to the right, so a chain of them reads from left to right. A cast binds more tightly than*, so(int)d * 2converts first.
// + groups to the left, so the order of the operands changes the result.
console.log(1 + 2 + "3", "1" + 2 + 3);
// ** groups to the right, and assignment too.
let a, b;
a = b = 2 ** 3 ** 2;
console.log(a, b);
// Some mixes are syntax errors, so the parser forces parentheses.
for (const src of ["-2 ** 2", "null ?? 0 || 1", "(null ?? 0) || 1", "(-2) ** 2"]) {
try {
console.log(src, "=>", new Function(`return ${src}`)());
} catch (e) {
console.log(src, "=>", e.name);
}
}
// typeof binds more tightly than +, and ! more tightly than instanceof.
console.log(typeof 1 + 2, !{} instanceof Object);
// Comparisons do not chain: 3 > 2 > 1 is (3 > 2) > 1, and true converts to 1.
console.log(3 > 2 > 1, 1 < 3 < 2);
33 123
512 512
-2 ** 2 => SyntaxError
null ?? 0 || 1 => SyntaxError
(null ?? 0) || 1 => 1
(-2) ** 2 => 4
number2 false
false true
- Verdict: native.
+groups to the left, so1 + 2 + "3"adds first and"1" + 2 + 3joins strings.**and=group to the right. JavaScript rejects-2 ** 2and a mix of??with||without parentheses, so the program cannot depend on a level that readers do not know.typeof 1 + 2is"number" + 2, and3 > 2 > 1is false because the first comparison givestrue, which converts to 1.
package main
import "fmt"
func main() {
// Go has five levels of binary precedence. & and << are at the level of *,
// so these mean (x & 1) == 0 and (1 << 2) + 1.
x := 6
fmt.Println(x&1 == 0, 1<<2+1)
// In C the same text means x & (1 == 0) and 1 << (2 + 1).
fmt.Println(x&(1-1), 1<<(2+1))
// && binds more tightly than ||.
t, f := true, false
fmt.Println(t || f && f, (t || f) && f)
// ++ and -- are statements, not operators in expressions, so i++ + 1 does not compile.
i := 1
i++
fmt.Println(i)
// gofmt shows the grouping with spaces: it removes the spaces around the operators that bind more tightly.
a, b, c := 2, 3, 4
y := a + b*c
z := a*b + c
fmt.Println(y, z)
}
true 5
0 8
true false
2
14 10
- Verdict: native. Go has five levels of binary operators, and
&,&^,<<and>>are at the level of*. Sox&1 == 0is(x & 1) == 0, and1<<2+1is 5, not 8 as in C.&&binds more tightly than||.++is a statement, not an operator in an expression.gofmtremoves the spaces around the operators that bind more tightly, soa + b*cshows its own grouping.
fn main() {
// A method call binds more tightly than unary minus, so this is -(2.pow(2)).
println!("{} {}", -2i32.pow(2), (-2i32).pow(2));
// As in Go, == binds less tightly than &, so this is (x & 1) == 0.
let x = 6;
println!("{}", x & 1 == 0);
// + binds more tightly than <<, as in C.
println!("{}", 1 << 2 + 1);
// `as` binds more tightly than the binary operators.
let big = 300i32;
println!("{} {}", big as u8 / 2, (big / 2) as u8);
// Comparisons do not associate: a < b < c is a compile error, so the program writes both tests.
let (a, b, c) = (1, 2, 3);
println!("{}", a < b && b < c);
// The ? operator binds more tightly than unary minus and the binary operators.
fn parse_neg(s: &str) -> Result<i32, std::num::ParseIntError> {
Ok(-s.parse::<i32>()? * 2)
}
println!("{:?} {}", parse_neg("21"), parse_neg("x").is_err());
}
-4 4
true
8
22 150
true
Ok(-42) true
- Verdict: native. A method call binds more tightly than unary minus, so
-2i32.pow(2)is −4. As in Go,==binds less tightly than&.+binds more tightly than<<, as in C.asbinds more tightly than/, sobig as u8 / 2truncates first. Comparisons do not associate, soa < b < cis a compile error. The?operator binds more tightly than unary minus and*.
Variations and related ideas
- No precedence. APL evaluates from right to left, and Smalltalk evaluates binary messages from left to right, so
2 + 3 * 4is 20 in Smalltalk11. Lisp writes prefix lists such as(+ 1 (* 2 3)), and Forth and PostScript use postfix, so no rule is needed. - User-defined levels. Haskell declares the level and the associativity of an operator with
infixl,infixrandinfix. Swift has precedence groups. Kotlin gives all named infix functions one level. - Parsing methods. A grammar can have one rule per level, as in recursive descent. Precedence climbing, Pratt parsing and the shunting yard algorithm read a table of levels instead10. See context-free grammars.
- Spreadsheets. In Microsoft Excel, unary minus binds more tightly than
^, so-3^2is 911.
Pitfalls
x & mask == 0in C-like languages. This testsx & (mask == 0). Write(x & mask) == 0. Compilers warn with-Wparentheses.- Shifts mixed with arithmetic.
1 << n + 1is1 << (n + 1)in C and(1 << n) + 1in Go. Use parentheses. - Unary minus and exponentiation.
-2 ** 2is −4 in Python, an error in JavaScript and 4 in Excel. Use parentheses. - String concatenation.
"total: " + a + bin Java or JavaScript joins the digits ofaandbinstead of adding them. Write"total: " + (a + b). - Chained comparisons.
a < b < cis a chain in Python, a compile error in Rust, and(a < b) < cin C and JavaScript, which compares 0 or 1 withc. - Precedence is not order. Parentheses change the grouping, not the order in which operands run. In C,
(i++) + (i++)is still undefined behavior. - Overloaded operators. A library that uses
^for power or<<for output keeps the built-in levels, so mixes with+or==may group in a way that the reader does not expect.
Cost
Precedence has no cost at run time: the parser builds the tree once, and the compiled code is the same as with explicit parentheses. A precedence-climbing or Pratt parser takes O(n) time for n tokens, with recursion as deep as the number of levels or the nesting of parentheses. A grammar with one rule per level does the same work with more function calls, which matters only in parsers that run very often.
History
The FORTRAN I compiler of 1957 grouped expressions by inserting parentheses: it replaced + with ))+(( and * with )*( and added parentheses at the ends, so that an ordinary parser could read the result10. Edsger W. Dijkstra's shunting yard algorithm converts infix expressions with a stack, and Vaughan Pratt described top-down operator precedence parsing in a 1973 paper10.
C inherited a level for & and | from B, where they also served as Boolean operators in conditions. When Dennis Ritchie split off && and ||, he kept the level of & relative to == to make the conversion of B code easy, and he later wrote that "Their tardy introduction explains an infelicity of C's precedence rules"9. Java, C#, JavaScript and C++ copied the C table, and Go and Rust changed the levels of the bitwise operators36.
References
- Expressions, The Python Language Reference, 6.5 The power operator; 6.17 Operator precedence
- Operator precedence, MDN Web Docs, Precedence and associativity
- The Go Programming Language Specification, Operator precedence
- Operators, The Java Tutorials, Operator Precedence
- C# operators and expressions, C# language reference, Operator precedence
- Expressions, The Rust Reference, Expression precedence
- C Operator Precedence, cppreference.com, Notes
- C++ Operator Precedence, cppreference.com, Notes
- The Development of the C Language, Dennis M. Ritchie, Embryonic C
- Operator-precedence parser, Wikipedia, Full parenthesization; Pratt parsing
- Order of operations, Wikipedia, Programming languages
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 4TQ4HF Edit this page History Report an error Markdown