Conceptcore
Order of evaluation
Also called evaluation order, sequence points, sequenced before, unsequenced, operand order.
The order of evaluation decides when each operand, argument and side effect of an expression happens. Some languages fix it from left to right, and C and C++ leave most of it open.
- Applies to
- core-languages
Idea
An expression such as f() + g() * h() has three calls. Precedence says that the product is computed before the sum. It does not say which call runs first. The order of evaluation is the rule that decides when each operand, each argument and each side effect happens. When the operands have no side effects, the order cannot be seen and does not matter. When they print, write to a variable or read a variable that another operand changes, the order decides the result.
Languages take one of three positions. Some fix the order, usually from left to right. Some leave it unspecified, so that the compiler can choose. Some leave it unspecified and also make some programs undefined if they depend on it. Python is in the first group, and the three calls run from left to right even though * binds tighter than +:
def f(name, value):
print("evaluate", name)
return value
print(f("a", 1) + f("b", 2) * f("c", 3))
evaluate a
evaluate b
evaluate c
7
The same expression in C can call the three functions in any of the six orders. A program that is correct on one compiler can print a different result on another compiler, or at another optimization level, with no change to the source.
How it works
Precedence is not order. Precedence and associativity decide the shape of the expression tree: which operator gets which operands. The order of evaluation decides the order in which the program walks that tree. MDN states the difference for JavaScript: precedence decides the grouping of operators, "but not the order of evaluation of operands", and the operands are always evaluated from left to right.1 The C# specification gives the same rule with an example. In F(i) + G(i++) * H(i), F gets the old value of i, G gets the old value, and H gets the new value, which "is separate from and unrelated to operator precedence".2 A tree has many valid walks. A language with a fixed order chooses one of them. A language without one lets the compiler choose any walk that computes each operand before the operator that uses it.
A fixed order. Python states: "Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side."3 Java guarantees that the operands "appear to be evaluated in a specific evaluation order, namely, from left to right". The left operand of a binary operator is fully evaluated before any part of the right operand, and each argument of a call is fully evaluated before any argument to its right.4 In a compound assignment such as a += e, Java saves the value of a before it evaluates e. ECMAScript describes each binary operator as steps: evaluate the left operand, get its value, then evaluate the right operand.5 The Rust Reference states that expressions with many operands "are evaluated left to right as written in the source code".6
A fixed order is a rule about what the program can observe. The word "appear" in the Java text is important. The compiler can still reorder, combine or remove operations if no program can see the difference. It cannot move a call before another call, because a call can have side effects.
Partial orders. Go fixes only part of the order. Function calls, method calls, receive operations and the logical operators are evaluated in lexical left-to-right order. The order of other events, such as reading a variable, compared to those calls is not specified. The specification gives the example x := []int{a, f()}, where x "may be [1, 2] or [2, 2]" if f changes a.7 An assignment in Go has two phases. First, the index expressions and pointer indirections on the left and all the expressions on the right are evaluated. Second, the assignments are done from left to right.8 So a, b = b, a swaps two variables, and i, x[i] = 1, 2 sets x[0], not x[1].
Sequencing in C. C has no general order. The standard says: "Except as specified later, side effects and value computations of subexpressions are unsequenced."9 The specified cases are few. &&, ||, ?: and the comma operator evaluate their first operand completely before the rest. A function call has a sequence point after the evaluation of the function designator and the arguments, and before the call. The arguments themselves are evaluated in no fixed order, and the standard gives an example in which four functions "may be called in any order".10 GCC describes the result as a partial order: if two functions are called in one expression with no sequence point between them, the order of the calls is not specified.11
C goes further than an unspecified order. "If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined."9 So i = i++ + 1 and a[i] = i++ are not programs with two possible results. They have no defined meaning, and the compiler can assume that they never run. This rule is one source of undefined behavior.
C++17. C++ had the C rules until 2017. In 2016, Gabriel Dos Reis, Herb Sutter and Jonathan Caves proposed a fixed order for some operators. Their paper asks what m[0] = m.size() stores in a map, and notes that f(i++, i) and v[i] = i++ were undefined.12 C++17 adopted most of the proposal. In E1[E2], E1.E2, E1 << E2 and E1 >> E2, the left operand is sequenced first. In E1 = E2 and in compound assignment, the right operand is sequenced first. The function name is sequenced before the arguments, but the arguments are still indeterminately sequenced, so each one is evaluated completely but in an order that the compiler chooses. cppreference sums up the general rule: "There is no concept of left-to-right or right-to-left evaluation in C++."13
Why leave it open. An open order lets a compiler pick the walk that uses the fewest registers, or evaluate the arguments of a call in the order that the calling convention pushes them. GCC on x86-64 often evaluates the arguments of a call from right to left, and Clang from left to right. A fixed order removes a class of bugs and makes a program mean the same thing on each compiler. Java and C# were designed with a fixed order. C++17 added one for the cases where idiomatic code, such as chained << and chained method calls, broke most often.
Declarative languages. SQL describes a result, not steps. PostgreSQL states: "The order of evaluation of subexpressions is not defined. In particular, the inputs of an operator or function are not necessarily evaluated left-to-right or in any other fixed order." The planner can rearrange AND and OR terms in WHERE and HAVING by the laws of Boolean algebra, so x <> 0 AND y / x > 1.5 does not protect the division. A CASE expression is the documented way to force an order.14
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Absent | |
| Java | Native | |
| C | Absent | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | Operands and arguments are evaluated from left to right, as on the JVM; no example file because kotlinc is not installed on the machine that recorded the examples. |
| SQL | Absent | |
| Bash | Native | |
| PowerShell | Native | Operands and pipeline stages are evaluated from left to right; no example file because pwsh is not installed on the machine that recorded the examples. |
| HTML | Does not apply | HTML has no expressions. |
| CSS | Does not apply | CSS functions such as calc() have no side effects, so the order of evaluation cannot be seen. |
| Regular expressions | Does not apply | A regular expression has no side effects, so the order of evaluation cannot be seen. |
| Language | Verdict | Order |
|---|---|---|
| Python | native | left to right, but the right side of an assignment first |
| JavaScript | native | left to right |
| TypeScript | native | left to right, as JavaScript |
| Java | native | left to right, left operand saved first |
| Kotlin | native | left to right |
| C# | native | left to right |
| Go | native | calls and logical operators left to right, other reads unspecified |
| Rust | native | left to right, but the right side first in primitive compound assignment |
| C | absent | unspecified, undefined for unsequenced changes |
| C++ | absent | unspecified, with fixed rules for some operators in C++17 |
| Bash | native | commands and words left to right |
| PowerShell | native | left to right |
| SQL | absent | not defined, use CASE to force an order |
| Regex, HTML, CSS | n/a | no side effects to order |
Python evaluates from left to right, with the right-hand side of an assignment before the target. A dictionary display evaluates each key before its value. A dictionary comprehension does the same in Python 3.8 and later versions.15
JavaScript and TypeScript evaluate operands, array elements and arguments from left to right. A compound assignment such as total += await f() reads total before the await, which loses updates when two async calls interleave.
Java and C# evaluate from left to right, and save the value of the left operand of a compound assignment before they evaluate the right operand. So a += (a = 3) with a equal to 9 gives 12 in both languages. Kotlin compiles to the same JVM model and also evaluates from left to right.
Go orders calls, receives and the logical operators from left to right, but not plain reads of variables compared to those calls. The gc compiler reads a after the call in []int{a, f()}.
Rust evaluates from left to right with one exception. For a compound assignment where both operands are primitive types, "the right hand side is evaluated first, the left hand side is evaluated next". For other types, += is a call to a trait method and the left side comes first. The Reference warns that code must not depend on the difference.16
C leaves the order unspecified and makes unsequenced changes to one object undefined. GCC warns with -Wsequence-point and Clang with -Wunsequenced. Both warnings are in -Wall.
C++ has the C rules plus the C++17 sequencing rules for subscripts, member access, shifts and assignment. The arguments of a call are still in an unspecified order.
Bash runs the commands of a list from left to right, and && and || decide whether the next command runs. It expands the words of a command from left to right.
SQL has no defined order inside an expression. CASE and the short-circuit rules of a given database are the only tools to control it.
def f(name, value):
print("evaluate", name)
return value
print(f("a", 1) + f("b", 2) * f("c", 3))
d = {}
d[f("key", "k")] = f("value", "v")
print(d)
evaluate a
evaluate b
evaluate c
7
evaluate value
evaluate key
{'k': 'v'}
- Verdict: native. The language reference states that Python evaluates expressions from left to right. Precedence makes
*bind tighter than+, butais still evaluated first. - In an assignment, the right-hand side is evaluated before the left-hand side. The value is computed before the key of the target.
- A dictionary display evaluates each key before its value. Since Python 3.8, a dictionary comprehension does the same. Before 3.8, CPython evaluated the value first in a comprehension.
This code runs but gives a wrong answer on purpose.
def add(item, items=[]):
items.append(item)
return items
print(add(1))
print(add(2))
[1]
[1, 2]
A default value is evaluated once, when the def statement runs, and not at each call. All the calls share the same list. Use items=None and make a new list in the body.
#include <iostream>
#include <map>
#include <string>
int f(const std::string& name, int value) {
std::cout << "evaluate " << name << "\n";
return value;
}
int main() {
std::cout << f("a", 1) << " " << f("b", 2) << "\n";
std::map<int, std::size_t> sizes;
sizes[7] = sizes.size();
std::cout << sizes[7] << "\n";
}
evaluate a
1 evaluate b
2
0
- Verdict: absent. C++ has no general left-to-right rule. Most operands and all function arguments are evaluated in an unspecified order.
- C++17 added an order for some operators. In
E1 << E2andE1 >> E2,E1is sequenced first. InE1 = E2,E2is sequenced first. InE1[E2]andE1.E2,E1is sequenced first. - So
sizes.size()runs beforesizes[7]inserts the key, and the value is 0. Before C++17, the value could be 0 or 1. - The output shows that
<<orders only the operands that are chained.f("a", 1)is evaluated, then its value is printed, thenf("b", 2)is evaluated.
#include <iostream>
int f(const char* name) {
std::cout << name;
return 0;
}
void g(int, int) {}
int main() {
g(f("a"), f("b"));
std::cout << "\n";
}
The arguments of a call are still indeterminately sequenced in C++17. GCC on x86-64 usually prints ba, and Clang usually prints ab. Both are correct.
public class Main {
static int f(String name, int value) {
System.out.println("evaluate " + name);
return value;
}
public static void main(String[] args) {
System.out.println(f("a", 1) + f("b", 2) * f("c", 3));
int a = 9;
a += (a = 3);
int b = 9;
b = b + (b = 3);
System.out.println(a + " " + b);
}
}
evaluate a
evaluate b
evaluate c
7
12 12
- Verdict: native. The Java Language Specification guarantees that the operands of an operator appear to be evaluated from left to right. The left operand is fully evaluated before any part of the right operand.
- In a compound assignment, the value of the left-hand variable is saved before the right-hand side is evaluated. So
a += (a = 3)adds 3 to the saved 9. - The specification still recommends that code does not depend on this rule.
This code runs but gives a wrong answer on purpose.
public class Main {
public static void main(String[] args) {
int count = 0;
for (int n = 0; n < 3; n++) {
count = count++;
}
System.out.println(count);
}
}
0
count++ gives the old value, 0, and then increments count. The assignment then stores the old value back. The increment is lost at each step. Write count++; as its own statement.
#include <stdio.h>
static int f(const char *name, int value) {
printf("evaluate %s\n", name);
return value;
}
int main(void) {
int both = f("left", 0) && f("right", 1);
int last = (f("first", 1), f("second", 2));
int pick = f("test", 1) ? f("then", 3) : f("else", 4);
printf("%d %d %d\n", both, last, pick);
return 0;
}
evaluate left
evaluate first
evaluate second
evaluate test
evaluate then
0 2 3
- Verdict: absent. Except for a few operators, the order in which C evaluates subexpressions is unspecified. The standard says that the side effects and value computations of subexpressions are unsequenced.
&&,||,?:and the comma operator have a sequence point after their first operand. Only these operators give a fixed order.&&stops afterleftbecause the result is already false.- The arguments of a call can be evaluated in any order. There is a sequence point after the arguments and before the call.
This code does not compile, on purpose.
#include <stdio.h>
int main(void) {
int i = 1;
int j = i++ + i++;
printf("%d\n", j);
return 0;
}
Two changes to i with no sequence point between them are undefined behavior, not only an unspecified order. GCC reports this with -Wsequence-point and Clang reports it with -Wunsequenced. Both are in -Wall, and Clang accepts the GCC name. The flag makes the warning an error.
static int F(string name, int value)
{
Console.WriteLine($"evaluate {name}={value}");
return value;
}
int i = 1;
int result = F("F", i) + F("G", i++) * F("H", i);
Console.WriteLine(result);
int a = 9;
a += (a = 3);
Console.WriteLine(a);
evaluate F=1
evaluate G=1
evaluate H=2
3
12
- Verdict: native. The C# specification states that the operands of an expression are evaluated from left to right. Its example is
F(i) + G(i++) * H(i):Fgets the old value ofi,Ggets the old value, andHgets the new value. - Precedence decides only that the multiplication happens before the addition. It does not move the call to
Fto a later point. - The left operand of a compound assignment is evaluated once and first, as in Java.
function f(name, value) {
console.log("evaluate", name);
return value;
}
console.log(f("a", 2) ** f("b", 3) ** f("c", 2));
let i = 0;
const values = [i++, i++, i];
console.log(values);
evaluate a
evaluate b
evaluate c
512
[ 0, 1, 2 ]
- Verdict: native. ECMAScript evaluates the operands of an operator from left to right. Precedence and associativity only group the operators.
**groups from the right, so the value is2 ** (3 ** 2), butais still evaluated first. - The elements of an array literal and the arguments of a call are evaluated from left to right, with each side effect complete before the next element.
This code runs but gives a wrong answer on purpose.
let total = 0;
async function add(amount) {
total += await Promise.resolve(amount);
}
await Promise.all([add(1), add(2)]);
console.log(total);
2
total += x reads total before it evaluates the right-hand side. Both calls read 0, then wait. Each one then writes its own sum, and the second write replaces the first. Await the value into a local variable first, then add it: const n = await ...; total += n;.
function f<T>(name: string, value: T): T {
console.log("evaluate", name);
return value;
}
const point = { x: f("x", 1), y: f("y", 2) };
const sum = f("left", point.x) + f("right", point.y);
console.log(sum);
evaluate x
evaluate y
evaluate left
evaluate right
3
- Verdict: native. TypeScript compiles to JavaScript and keeps its order of evaluation. Property values in an object literal and the operands of
+are evaluated from left to right. - The type checker does not look at side effects, so it does not warn about code that depends on the order.
package main
import "fmt"
func f(name string, value int) int {
fmt.Println("evaluate", name)
return value
}
func main() {
fmt.Println(f("a", 1) + f("b", 2)*f("c", 3))
x := []int{0, 0}
i := 0
i, x[i] = 1, 9
fmt.Println(i, x)
}
evaluate a
evaluate b
evaluate c
7
1 [9 0]
- Verdict: native. The Go specification says that function calls, method calls, receive operations and the logical operators
&&and||are evaluated in lexical left-to-right order. - An assignment has two phases. First, the index expressions and pointer indirections on the left and the expressions on the right are evaluated in the usual order. Second, the assignments are done from left to right. So
x[i]uses the oldi, which is 0. - The order of other operations, such as reading a variable, compared to these calls is not specified.
This code runs but gives a wrong answer on purpose.
package main
import "fmt"
func main() {
a := 1
next := func() int {
a++
return a
}
x := []int{a, next()}
fmt.Println(x)
}
[2 2]
The specification gives this case: x may be [1, 2] or [2, 2], because the read of a is not ordered compared to the call. The gc compiler reads a after the call. Put the call in its own statement before the literal.
use std::num::Wrapping;
fn index(side: &str) -> usize {
println!("{side}: index");
0
}
fn value(side: &str) -> i32 {
println!("{side}: value");
1
}
fn main() {
let mut plain = [10, 20];
plain[index("plain")] += value("plain");
let mut wrapped = [Wrapping(10), Wrapping(20)];
wrapped[index("wrapped")] += Wrapping(value("wrapped"));
println!("{} {}", plain[0], wrapped[0]);
}
plain: value
plain: index
wrapped: index
wrapped: value
11 11
- Verdict: native. The Rust Reference states that the operands of an expression are evaluated from left to right as written, and that the arguments of a call are evaluated from left to right.
- Compound assignment is the exception. When both operands are primitive types, the right-hand side is evaluated first. When either operand is another type,
+=is a call toAddAssign::add_assignand the left-hand side is evaluated first.Wrapping<i32>is not primitive, so the two lines give opposite orders. - The Reference warns that code must not depend on this difference.
- Rust has no undefined behavior from evaluation order in safe code, because the borrow checker does not let one expression change a variable while another part of the expression borrows it.
CREATE TABLE items (name TEXT, total INTEGER, count INTEGER);
INSERT INTO items VALUES ('a', 10, 2), ('b', 5, 0), ('c', 9, 3);
SELECT name,
CASE WHEN count > 0 THEN total / count ELSE NULL END AS average
FROM items
ORDER BY name;
a|5
b|
c|3
- Verdict: absent. SQL describes a result, not steps. The order in which a database evaluates the parts of an expression is not defined. PostgreSQL states that the inputs of an operator or function are not necessarily evaluated left to right, and that the planner can reorder
ANDandORterms inWHEREandHAVING. - So
WHERE count > 0 AND total / count > 2does not protect the division.CASEevaluates its branches in order, and is the documented way to force an order. - SQLite returns NULL for division by zero, so this example does not fail without the guard there. PostgreSQL raises an error.
check() {
echo "check $1"
return "$2"
}
check a 0 && check b 1 || echo "fallback"
check c 1 || check d 0 && echo "done"
check a
check b
fallback
check c
check d
done
- Verdict: native. In a list, Bash runs the commands from left to right.
&&runs the next command only if the last status was 0, and||runs it only if the status was not 0. The two operators have equal precedence and group from the left. - Words in a command are expanded from left to right before the command runs.
This code runs but gives a wrong answer on purpose.
deploy() {
echo "deploy"
return 0
}
notify() {
echo "notify failed"
return 1
}
deploy && notify || echo "deploy failed"
deploy
notify failed
deploy failed
a && b || c is not an if-then-else. When b fails, c runs too. Here the deploy succeeded, but the script says that it failed. Use if deploy; then notify; else echo "deploy failed"; fi.
Variations and related ideas
- Short-circuit evaluation.
&&,||and the conditional operator evaluate the second operand only when it is needed. They are the only operators with a fixed order in C, and the order is part of their meaning. - Evaluation strategy. Strict languages evaluate the arguments of a call before the call. Lazy languages, such as Haskell, evaluate an argument only when its value is needed, so the order of evaluation is decided by data dependencies and not by the text.
- Sequence points and sequenced-before. C89 described the order with sequence points. C11 and C++11 replaced them with the "sequenced before" relation, which can also describe the order between threads.
- Reordering by the compiler and the hardware. Even with a fixed order in the language, the compiler and the processor can reorder memory operations that another thread can see. The rules for that are part of the memory model of the language. See data races.
- Pure functions. If no operand has a side effect, every order gives the same result. Code that uses pure functions does not depend on the order of evaluation. See higher-order functions.
Pitfalls
- Precedence read as order.
f() + g() * h()does not callgandhbeforefin Python, Java or C#. Precedence only builds the tree. - A variable changed and read in one expression.
i = i++,a[i] = i++andf(i, i++)are undefined in C and were undefined in C++ before C++17. In Java,count = count++is defined but leavescountunchanged. - The order of arguments. In C and C++,
printf("%d %d", next(), next())can print the two values in either order. GCC and Clang choose differently. Assign each call to a variable first. - Reads that are not calls in Go.
[]int{a, f()}can readabefore or afterfchanges it. - Guards in SQL.
WHERE x <> 0 AND y / x > 1can divide by zero, because the planner can evaluate the division first. UseCASE. - Compound assignment across an
awaitor a yield point. In JavaScript,total += await f()readstotalbefore it waits. Another task can changetotalin the meantime, and its change is lost. a && b || cin shell scripts. Ifbfails,cruns too. It is not an if-then-else.- Default arguments. Python evaluates a default value once, when the function is defined, and not at each call.
Cost
A fixed order has a small cost in some cases. The compiler cannot evaluate the arguments in the order that suits the calling convention or the register allocator. In practice, most operands have no side effects that the compiler cannot see, and for those the compiler is free to reorder. The P0145 authors changed the Visual C++ compiler to force left-to-right evaluation of all call arguments, with no new optimizations. On the SPEC benchmarks, some entries ran slower and some ran faster, and the variation was between -4% and +4%. One test out of 26 in a large application code base failed, because the code depended on the old order.12
An unspecified order has a cost for the programmer. Code that depends on the order works on one compiler and fails on another, and the failure appears only after a change of compiler, flags or platform.
History
ALGOL 60 stated a general rule: "The sequence of operations within one expression is generally from left to right", with extra rules for precedence and parentheses.17 The text was about the order of operators, and it did not settle when the side effects of function designators happen. Later languages took different positions. C left the order unspecified so that compilers on many machines could generate efficient code, and the C standards of 1989 and later added sequence points and the rule that makes unsequenced changes undefined. Java, in 1996, and C# then chose a fixed left-to-right order. C++ adopted P0145 in C++17, after a paper of 2014 and its revision of 2016, and fixed the order for the operators where idiomatic code broke most often.12 Python had a left-to-right rule for expressions, and fixed the order of keys and values in dictionary comprehensions in Python 3.8.15
References
- Operator precedence, MDN Web Docs, Precedence and order of evaluation
- C# language specification, Expressions, 12.4.1 Operators, General
- The Python Language Reference, Expressions, Python 3.14, 6.16 Evaluation order
- The Java Language Specification, Java SE 25 Edition, 15.7 Evaluation Order
- ECMAScript Language Specification, 13.15.4 EvaluateStringOrNumericBinaryExpression
- The Rust Reference, Expressions, Evaluation order of operands
- The Go Programming Language Specification, Order of evaluation
- The Go Programming Language Specification, Assignment statements
- ISO/IEC 9899:201x Committee Draft N1570, 6.5 Expressions, paragraphs 2 and 3
- ISO/IEC 9899:201x Committee Draft N1570, 6.5.2.2 Function calls, paragraphs 10 and 12
- GCC Manual, Options to Request or Suppress Warnings, -Wsequence-point
- Refining Expression Evaluation Order for Idiomatic C++, P0145R3, G. Dos Reis, H. Sutter, J. Caves, 2016, 1 Introduction, 7 Implementation experience report
- Order of evaluation, cppreference.com, Rules, Undefined behavior
- PostgreSQL Documentation, Value Expressions, 4.2.14 Expression Evaluation Rules
- The Python Language Reference, Expressions, Python 3.14, 6.2.7 Dictionary displays
- The Rust Reference, Operator expressions, Compound assignment expressions
- Revised Report on the Algorithmic Language ALGOL 60, P. Naur (ed.), Communications of the ACM 6(1), 1963, 3.3.5 Precedence of operators
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 SWPCV3 Edit this page History Report an error Markdown