Conceptcore
Statements and expressions
Also called expression, statement, expression statement, assignment expression, conditional expression, ternary operator, expression language, block expression, switch expression.
An expression has a value, and a statement does something. Languages differ in where they draw the line, such as whether assignment, if and blocks give values.
- Applies to
- core-languages
Idea
An expression is a piece of code that has a value, such as 2 + 3, f(x) or a > b. A statement is a piece of code that does something, such as an assignment, a loop or a return, and in many languages has no value. Programs are built from both: statements give the order of the steps, and expressions compute the values that the steps use. Languages draw the line between them in different places. In C, assignment is an expression; in Go and Python, it is a statement. In Rust, Kotlin and the functional languages, if and blocks are expressions with values; in C, Java and Python, if is a statement.
import ast
code = "x = 2 + 3\nprint(x * 2)\nif x > 4:\n x = 0\n"
for stmt in ast.parse(code).body: # a program is a list of statements
inner = [type(n).__name__ for n in ast.walk(stmt) if isinstance(n, ast.expr)]
print(f"{type(stmt).__name__:6} contains {inner}")
print(eval("2 + 3")) # an expression has a value
env = {}
print(exec("x = 2 + 3", env), env["x"]) # a statement has an effect
try:
eval("x = 2 + 3")
except SyntaxError:
print("an assignment statement is not an expression")
print((y := 2 + 3) * 2, y) # an assignment expression has both
Assign contains ['Name', 'BinOp', 'Constant', 'Constant']
Expr contains ['Call', 'Name', 'BinOp', 'Name', 'Constant']
If contains ['Compare', 'Name', 'Constant', 'Name', 'Constant']
5
None 5
an assignment statement is not an expression
10 5
The parser of Python turns the four lines into three statements, an assignment, an expression statement and an if, and each statement contains expressions: names, constants, a binary operation, a call and a comparison. eval takes an expression and returns its value, exec takes statements and returns nothing but changes the namespace, and eval rejects an assignment because an assignment is not an expression in Python. The assignment expression := is the exception that has both a value and an effect.
How it works
Expressions compute values. The C++ reference defines the term: "An expression is a sequence of operators and operands, that specifies a computation. Expression evaluation may produce a result (e.g., evaluation of 2 + 2 produces the result 4) and may generate side-effects".1 Expressions nest: the operands of an operator and the arguments of a call are themselves expressions, so a single expression can be a tree of any depth. Every expression has a type, and the language defines the order in which its parts run, or leaves some of that order open. See order of evaluation.
Statements run in sequence. A statement is a unit of execution. The Python reference lists the simple statements, among them assignment, return, raise, import and the expression statement, and says: "A simple statement is comprised within a single logical line."2 Compound statements such as if, while and def contain other statements. A block is a list of statements that run one after another, which is how a program states the order of its effects.
Expression statements. Most languages let an expression stand as a statement, and the value is thrown away. The Rust reference describes one: "An expression statement is one that evaluates an expression and ignores its result. As a rule, an expression statement’s purpose is to trigger the effects of evaluating its expression."3 The Python reference adds that expression statements are used "(mostly interactively) to compute and write a value, or (usually) to call a procedure".2 A function call for its effect, such as print(x), is the common case.
Assignment: statement or expression. In C and the languages that follow it, x = 5 is an expression whose value is 5. This allows a = b = 0 and while ((n = read()) > 0), and also the bug if (x = 0), which assigns instead of comparing. Python and Go make assignment a statement to prevent that bug. Python later added a separate operator for the useful cases: "An assignment expression (sometimes also called a “named expression” or “walrus”) assigns an expression to an identifier, while also returning the value of the expression."4
Expression languages. Some languages make almost everything an expression. The Rust reference says: "Rust is primarily an expression language. This means that most forms of value-producing or effect-causing evaluation are directed by the uniform syntax category of expressions."5 In Rust, Kotlin, Scala, Ruby and the Lisp and ML families, if, match and blocks have values, so a variable can take its value from a choice without a temporary that each branch assigns. Statement languages add expression forms over time: the conditional operator ?:, switch expressions in Java and C#, lambdas with expression bodies, and comprehensions. See pattern matching.
Values without effects. An expression with no side effects is easy to reason about: it can be replaced by its value, moved, cached or evaluated in parallel. Code that keeps effects in statements and computes in pure expressions is easier to test and to change, and functional languages build whole programs this way. See functional programming and immutability.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | As JavaScript, with the same statements and expressions and type annotations on top. |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | If, when and try are expressions with values, while assignment is a statement and loops are statements; no example file because kotlinc is not installed on the machine that recorded the examples. |
| SQL | Native | Statements such as SELECT and UPDATE contain expressions, and CASE is the conditional expression. |
| Bash | Native | Commands are statements, and arithmetic expansion and the test command give expressions; every command has an exit status that if and while test. |
| PowerShell | Native | Statements such as if and switch can produce output that an assignment captures, so they work as expressions; no example file because pwsh is not installed on the machine that recorded the examples. |
| HTML | Does not apply | Markup has no statements or values. |
| CSS | Does not apply | Declarations hold values, and calc() is an expression, but there are no statements to run. |
| Regular expressions | Does not apply | A pattern has no statements or values. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | statements and expressions; x if c else y; := |
| JavaScript | native | C-style; assignment, ?: and comma are expressions |
| TypeScript | native | as JavaScript |
| Java | native | C-style; switch expressions with yield |
| Kotlin | native | if, when and try are expressions |
| C# | native | C-style; switch expressions; ??=; throw expressions |
| Go | native | assignment and ++ are statements; no ?: |
| Rust | native | blocks, if, match and loop are expressions |
| C | native | assignment and comma are expressions; ?: |
| C++ | native | as C; lvalue expressions; lambdas called at once |
| Bash | native | commands as statements; $(( )) and [[ ]] |
| PowerShell | native | statements whose output can be assigned |
| SQL | native | statements containing expressions; CASE |
| Regex | n/a | no statements or values |
| HTML | n/a | no statements or values |
| CSS | n/a | declarations and calc(), no statements |
Every language with code has both, so the table records where the line falls. Each example file chooses a label from a score and, in most files, reads numbers until a zero. Python, JavaScript, Java, C and C# use the conditional operator or a switch expression to give a value; Go must use a switch statement with a return in each case. Rust needs neither a ternary operator nor a return, because match and blocks have values.
The files also show the two places where languages differ most. Assignment is an expression in JavaScript, Java, C#, C and C++, so their files read and test in one loop condition, and the wrong block of the C file shows the price. Assignment and ++ are statements in Go, as the fails block shows. The fails block of the Rust file shows the other side of an expression language: a single semicolon changes the value of a block.
def label_statement(score):
if score >= 90: # if is a statement: each branch assigns
label = "A"
elif score >= 50:
label = "pass"
else:
label = "fail"
return label
def label_expression(score): # a conditional expression has a value
return "A" if score >= 90 else "pass" if score >= 50 else "fail"
scores = [95, 70, 30]
print([label_statement(s) for s in scores])
print([label_expression(s) for s in scores])
data = iter([3, 1, 4, 0, 5])
total = 0
while (n := next(data)) != 0: # assign and test in one expression
total += n
print(total)
['A', 'pass', 'fail']
['A', 'pass', 'fail']
8
- Verdict: native. Python separates statements and expressions strictly:
if,while,for,defand=are statements, and an expression cannot contain them. The language adds expression forms for the common cases: the conditional expressiona if c else b, comprehensions in place of loops,lambdain place ofdef, and since Python 3.8 the assignment expression:=, which assigns and gives the value in one step.
#include <iostream>
#include <string>
int main() {
int score = 70;
const std::string label = [&] { // an immediately invoked lambda
if (score >= 90) return "A";
if (score >= 50) return "pass";
return "fail";
}(); // lets a const variable take its value from statements
std::cout << label << '\n';
int a = 1, b = 2;
(a < b ? a : b) = 0; // a conditional of two variables is a variable
std::cout << a << ' ' << b << '\n';
int x = 3;
int& r = (x += 2); // compound assignment gives the variable itself
r *= 10;
std::cout << x << '\n';
}
pass
0 2
50
- Verdict: native. C++ has the expressions of C, and some of them are lvalues, which name an object: a conditional of two variables of the same type is itself a variable, and compound assignment returns the variable it changed. A lambda that is called at once turns a block of statements into an expression, which lets a
constvariable take its value fromifstatements.
public class Main {
static String label(int score) {
return switch (score / 10) { // a switch expression has a value
case 10, 9 -> "A";
case 8, 7, 6, 5 -> "pass";
default -> {
String s = "fail";
yield s; // a block in a switch expression yields its value
}
};
}
public static void main(String[] args) {
System.out.println(label(95) + " " + label(70) + " " + label(30));
int a, b;
a = b = 5;
System.out.println(a + " " + b);
int[] data = {3, 1, 4, 0, 5};
int i = 0, n, total = 0;
while ((n = data[i++]) != 0) total += n;
System.out.println(total);
System.out.println(total > 5 ? "big" : "small");
}
}
A pass fail
5 5
8
big
- Verdict: native. Java has the statements and expressions of C, with assignment as an expression and
?:as the conditional expression. Since Java 14,switchcan also be an expression: each arrow case gives a value, a block case gives its value withyield, and the compiler checks that the cases cover every input.
#include <stdio.h>
static const char *label(int score) {
return score >= 90 ? "A" : score >= 50 ? "pass" : "fail";
}
int main(void) {
int scores[] = {95, 70, 30};
for (int k = 0; k < 3; k++) printf(k ? " %s" : "%s", label(scores[k]));
printf("\n");
int a, b;
a = b = 5; /* assignment is an expression */
printf("%d %d\n", a, b);
int data[] = {3, 1, 4, 0, 5};
int i = 0, n, total = 0;
while ((n = data[i++]) != 0) total += n;
printf("%d\n", total);
int c = (a++, a * 2); /* the comma operator: the value of the right side */
printf("%d %d\n", a, c);
return 0;
}
A pass fail
5 5
8
6 12
This code runs but gives a wrong answer on purpose.
#include <stdio.h>
int main(void) {
int errors = 3;
if (errors = 0) { /* meant ==; this assigns 0, and 0 is false */
printf("no errors\n");
} else {
printf("errors: %d\n", errors);
}
return 0;
}
errors: 0
- Verdict: native. In C, assignment is an expression, and any expression followed by a semicolon is a statement. This lets the loop read and test in one condition, and lets
a = b = 5assign twice. The comma operator evaluates its left side, then gives the value of its right side, socis 12 aftera++makesa6. - The wrong block writes
=where it means==. The condition assigns 0 toerrors, and 0 is false, so the program takes the else branch and prints 0 errors where there were 3. Compilers warn about an assignment used as a condition with-Wall; extra parentheses tell them it is meant.
static string Label(int score) => score switch
{
>= 90 => "A",
>= 50 => "pass",
_ => "fail",
};
Console.WriteLine(string.Join(" ", new[] { 95, 70, 30 }.Select(Label)));
int a, b;
a = b = 5;
Console.WriteLine($"{a} {b}");
string? name = null;
name ??= "guest"; // assign only when null; the expression has the value
Console.WriteLine(name);
Console.WriteLine((name.Length > 3 ? "long" : "short") + " name");
A pass fail
5 5
guest
long name
- Verdict: native. C# has the statements and expressions of C and adds expression forms: the
switchexpression with patterns, expression-bodied members with=>,??and??=for null, andthrowas an expression. Assignment, including??=, is an expression whose value is the assigned value.
const label = (score) => (score >= 90 ? "A" : score >= 50 ? "pass" : "fail");
console.log([95, 70, 30].map(label));
let a, b;
a = b = 5; // assignment is an expression whose value is the assigned value
console.log(a, b);
const data = [3, 1, 4, 0, 5];
let i = 0, n, total = 0;
while ((n = data[i++]) !== 0) total += n;
console.log(total);
const x = (console.log("side effect"), 42); // the comma operator
console.log(x);
[ 'A', 'pass', 'fail' ]
5 5
8
side effect
42
- Verdict: native. JavaScript follows C:
if,forandwhileare statements, while assignment, the conditional operator?:and the comma operator are expressions.a = b = 5works because the value ofb = 5is 5. An arrow function with an expression body returns that expression, so short functions need noreturnstatement.
package main
import "fmt"
func label(score int) string {
switch { // switch and if are statements in Go
case score >= 90:
return "A"
case score >= 50:
return "pass"
default:
return "fail"
}
}
func main() {
fmt.Println(label(95), label(70), label(30))
x := 5
x++ // a statement, not an expression
if y := x * 2; y > 10 { // a simple statement before the condition
fmt.Println("y is", y)
}
fmt.Println(x)
}
A pass fail
y is 12
6
This code does not compile, on purpose.
package main
import "fmt"
func main() {
x := 5
y := x++ // x++ is a statement, so it has no value
fmt.Println(x, y)
}
- Verdict: native. Go keeps expressions small. Assignment,
++and--are statements, there is no conditional operator, andifandswitchare statements, so a choice between two values needs anifthat assigns or a function that returns. Aniforswitchcan start with a short statement, such asy := x * 2, whose names are visible only inside it. - The fails block uses
x++as a value. In Go it is a statement with no value, so the compiler rejectsy := x++, which removes the C puzzle of the order ofx++inside larger expressions.
fn label(score: u32) -> &'static str {
match score {
90.. => "A",
50..=89 => "pass",
_ => "fail",
} // the match is the last expression, so it is the return value
}
fn main() {
let labels: Vec<_> = [95, 70, 30].into_iter().map(label).collect();
println!("{labels:?}");
let area = {
let w = 3;
let h = 4;
w * h // no semicolon: the block has this value
};
let sign = if area > 10 { "big" } else { "small" };
println!("{area} {sign}");
let data = [3, 1, 4, 0, 5];
let mut i = 0;
let total = loop {
if data[i] == 0 {
break data[..i].iter().sum::<i32>(); // break with a value
}
i += 1;
};
println!("{total}");
let unit: () = (); // a statement has the value of type ()
println!("{unit:?}");
}
["A", "pass", "fail"]
12 big
8
()
This code does not compile, on purpose. The error is E0308.
fn area(w: u32, h: u32) -> u32 {
w * h; // the semicolon makes this a statement, so the body has no value
}
fn main() {
println!("{}", area(3, 4));
}
- Verdict: native. Rust is an expression language. Blocks,
if,matchandloopare expressions with values, the last expression of a block without a semicolon is the value of the block, andbreakcan carry a value out of aloop. A semicolon turns an expression into a statement, and a statement has the unit value(). - The fails block ends the body of
areawithw * h;. The semicolon makes the multiplication a statement, so the body has the value(), which does not match the return typeu32, and the compiler reports mismatched types and suggests removing the semicolon.
Variations and related ideas
- Side effects. An expression can change state, by an assignment, a call or
++, and the order of these effects inside one expression is a common source of bugs. See order of evaluation. - Conditional expressions.
c ? a : bin the C family,a if c else bin Python, andifexpressions in Rust and Kotlin choose a value without a statement. - Switch and match expressions. Java, C#, Rust and Kotlin give a value from the case that matches, and check that the cases cover every input. See pattern matching.
- Comprehensions and pipelines. List comprehensions and LINQ express loops as expressions that build a value. See higher-order functions.
- Lvalues and rvalues. In C and C++, some expressions name an object and can appear on the left of
=, while others are only values. - Statement expressions. GCC's
({ ... })extension and immediately invoked lambdas in C++ and JavaScript turn blocks of statements into expressions. - Everything is an expression. In Lisp, ML and Haskell there are no statements, and a program is one large expression.
Pitfalls
=for==. In languages where assignment is an expression, a condition that assigns compiles and gives a wrong result, as the wrong block of the C file shows. Use the warnings of the compiler, and put a constant on the left only if your team agrees to.- A semicolon that discards a value. In Rust, a semicolon after the last expression of a block makes its value
(), as the fails block of the Rust file shows. - Effects hidden in expressions.
a[i] = i++in C has undefined behavior, andf(x++, x)depends on the order of evaluation. Keep each side effect in its own statement. - Nested conditional expressions. Chains of
?:orif elseexpressions are hard to read past two levels. Use aswitchexpression or a statement. - Expression statements that do nothing.
x == 5;compiles in C and JavaScript and does nothing. Linters and compilers warn about unused values; enable those warnings. - Python's comma.
x = 1,makesxa tuple, because the comma, not the parentheses, makes a tuple expression.
Cost
The difference between expressions and statements costs nothing at run time: compilers translate both to the same instructions, and an if expression produces the same code as an if statement that assigns a temporary. The choice affects the cost of reading and changing code. Expression forms remove temporaries and make it clear that each branch gives a value, and the compiler can check that none is missing. Long expressions with side effects cost more to understand than the statements they replace.
History
FORTRAN, in 1957, separated arithmetic expressions from statements, and its name comes from the translation of formulas. Algol 60 in 1960 defined statements and expressions in a formal grammar and allowed conditional expressions, and Lisp in 1958 had no statements at all: every form was an expression with a value. Algol 68 made almost every construct an expression. BCPL, in 1967, had VALOF blocks that give a value, and C, in 1972, kept assignment as an expression with the conditional operator ?: and the comma operator.
Python, from 1991, made assignment a statement on purpose, and PEP 572 added the assignment expression := in Python 3.8 in 2019, after long debate. Go, in 2009, made ++ and assignment statements and left out the conditional operator. Rust, released in 2015, and Kotlin, in 2016, followed the ML family and made blocks and if expressions.5 Java 14 in 2020 and C# 8 in 2019 added switch expressions.
References
- Expressions, cppreference.com, Introduction
- Simple statements, The Python Language Reference, 7. Simple statements and 7.1 Expression statements
- Statements, The Rust Reference, Expression statements
- Expressions, The Python Language Reference, 6.12 Assignment expressions
- Statements and expressions, The Rust Reference, Introduction
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 98X2DH Edit this page History Report an error Markdown