Conceptcore
Side effect
Also called side effect, side effects, side-effect, effect, pure function, purity, impure function, referential transparency, observable effect.
A side effect is a change that a function makes beyond its return value, such as a write to a variable, a file or the screen. It makes the order and the number of calls matter.
- Applies to
- core-languages
Idea
A function has a side effect when calling it does something more than compute a value: it changes a variable outside itself, changes an object that the caller passed in, writes to a file, the screen or the network, or reads input that changes from call to call. A function with no side effects, whose result depends only on its arguments, is pure. A call to a pure function can be replaced by its value, called twice or not called at all, and the program means the same thing. A call with side effects cannot: the number of calls and their order change what the program does.
total = 0
def add(a, b): # no side effect: the result depends only on the arguments
return a + b
def add_and_count(a, b): # side effect: it changes a global variable
global total
total += a + b
return total
print("add:", add(2, 3), add(2, 3))
print("add_and_count:", add_and_count(2, 3), add_and_count(2, 3))
def shout(words): # side effect: it changes the caller's list
words.append("!")
return " ".join(words)
w = ["hello", "world"]
print(shout(w))
print(shout(w))
print("caller's list:", w)
log = []
def f(x): # side effect: it records each call
log.append(x)
return x
print("value:", f(1) + f(2) * f(3), "calls in order:", log)
total = 0
y = add_and_count(2, 3)
print("y + y =", y + y, end="; ")
total = 0
print("two calls give", add_and_count(2, 3) + add_and_count(2, 3))
add: 5 5
add_and_count: 5 10
hello world !
hello world ! !
caller's list: ['hello', 'world', '!', '!']
value: 7 calls in order: [1, 2, 3]
y + y = 10; two calls give 15
add gives 5 every time. add_and_count gives 5 and then 10 for the same arguments, because each call changes total. shout changes the list that the caller owns, so the second call adds a second "!". The function f records each call, which makes the order of evaluation visible: Python evaluates the operands from left to right. The last two lines show that a call with a side effect cannot be replaced by its value: storing the result once and adding it to itself gives 10, but two calls give 15.
How it works
What counts as a side effect. The C standard gives an exact list. A side effect is "access (read or write) to an object designated by a volatile lvalue, modification (writing) to an object", atomic synchronization, a change to a file or to the floating-point environment, "or calling a function that does any of those operations."1 In general terms, an expression has a side effect when it changes state that some other part of the program, or the world outside it, can observe. Reading changeable state, such as the clock, a global variable or input, is not a side effect in the C sense, but it makes a function impure in the same way, because the result no longer depends only on the arguments.
Pure functions and referential transparency. An expression is referentially transparent when it can be replaced by its value without a change in the meaning of the program. Pure functions give this property, and it allows a compiler and a reader to reason about code locally. GCC's pure attribute states the condition for C: "Calls to functions that have no observable effects on the state of the program other than to return a value may lend themselves to optimizations such as common subexpression elimination."2 .NET has a PureAttribute that "Indicates that a type or method is pure, that is, it does not make any visible state changes."9 Neither compiler checks that the claim is true.
Order and sequencing. Side effects make the order of evaluation part of the meaning. Each language states which effects happen before others. C and C++ define sequence points or the relation "sequenced before", and two unsequenced writes to one object are undefined behavior; C++ has rules such as "The value computations (but not the side effects) of the operands to any operator are sequenced before the value computation of the result of the operator".10 Java, C#, JavaScript and Python evaluate operands from left to right. A program that depends on the order of two calls should put them in separate statements.
Effects through parameters. A function can change its caller's data when it receives a reference to it: an object in Python, Java, JavaScript or C#, a pointer in C and Go, a slice or a map in Go, a reference in C++, or a &mut reference in Rust. In most languages, the signature does not show whether the function changes the argument. Rust does: a & reference allows only reads, and a change through it is a compile error. Libraries name the convention. Python's list.sort returns None: "To remind users that it operates by side effect, it does not return the sorted sequence (use sorted() to explicitly request a new sorted list instance)."4 JavaScript added copying methods in ECMAScript 2023: "The toSorted() method of Array instances is the copying version of the sort() method."6
Effects in lazy code. Lazy sequences and queries run their functions when a consumer asks for items, not when the code that builds them runs. A side effect in such a function happens at a time, and a number of times, that the reader does not see. Java warns: "Side-effects in behavioral parameters to stream operations are, in general, discouraged, as they can often lead to unwitting violations of the statelessness requirement, as well as other thread-safety hazards."7 Stream.count can skip the pipeline: "An implementation may choose to not execute the stream pipeline (either sequentially or in parallel) if it is capable of computing the count directly from the stream source."8 A LINQ query in C# runs again each time the program enumerates it.
Controlling effects. Most languages allow effects anywhere and rely on conventions: immutable values, functions that return new values, and effects at the edges of the program, around a core of pure functions. Haskell makes the separation part of the type system. Its tutorial says that I/O actions "are cleanly separated from the purely functional core of the language", and "A function such as f :: Int -> Int -> Int absolutely cannot do any I/O since IO does not appear in the returned type."3 Effect systems in Koka and the effect handlers of OCaml 5 track other kinds of effects in the same way.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | TypeScript allows effects anywhere, as JavaScript does, and readonly properties and ReadonlyArray reject some writes when the program compiles, but no example file exists. |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | Kotlin allows effects anywhere, and val and the read-only interfaces List and Map prevent some changes, but no example file exists because kotlinc is not installed. |
| SQL | Native | SELECT reads data, and INSERT, UPDATE and DELETE change it; functions can be marked deterministic or immutable in some systems. |
| Bash | Native | Commands act on files and the environment, and a subshell or a pipeline stage runs in a copy of the shell, so its changes to variables are lost, but no example file exists. |
| PowerShell | Native | Cmdlets that change the system support -WhatIf and -Confirm, which show or ask before the effect, but no example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML is markup and has no evaluation. |
| CSS | Does not apply | CSS rules have no evaluation that changes state. |
| Regular expressions | Does not apply | A pattern matches text and has no side effects. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | effects anywhere; sorted against list.sort; tuples and frozen dataclasses |
| JavaScript | native | effects anywhere; copying methods such as toSorted; Object.freeze |
| TypeScript | native | as JavaScript; readonly types prevent some writes |
| Java | native | effects anywhere; immutable collections; stream rules |
| Kotlin | native | val, read-only collection interfaces |
| C# | native | readonly, records with with, [Pure] with no check |
| Go | native | value parameters copy; pointers, slices and maps share |
| Rust | native | & and &mut show effects on arguments in the signature |
| C | native | const pointers; GCC pure and const attributes |
| C++ | native | const references and methods; mutable for hidden caches |
| Bash | native | commands act on files and the environment; subshells isolate changes |
| PowerShell | native | cmdlets with effects support -WhatIf |
| SQL | native | SELECT reads; INSERT, UPDATE and DELETE change data |
| Regex | n/a | a pattern has no side effects |
| HTML | n/a | markup has no evaluation |
| CSS | n/a | rules have no evaluation |
Every general-purpose language on this list allows side effects anywhere in a function, so the verdict is native for each. They differ in how much the code shows. Rust shows effects on arguments in the types, C and C++ show them with the absence of const, and Go shows them with pointers, although slices and maps share data with no pointer in sight. Python, Java, JavaScript and C# show nothing in the signature, and the convention of the library tells the reader, as in sort against sorted. SQL separates queries from statements that change data, and a query is close to a pure function of the tables.
The example files show these points. Python shows list.sort against sorted and the shared default list. JavaScript shows toSorted and the shallow Object.freeze. Java shows a read-only view that still changes, and lazy streams that run a peek late or never. C# shows a deferred query that runs its lambda each time. Go shows which parameters share data. Rust shows the compile error for a change through &. C shows a static counter and a macro that runs its argument twice. C++ shows a const method that changes a mutable cache.
scores = [58, 12, 90, 31]
result = scores.sort() # sorts in place and returns None
print("sort returned", result, "and changed scores to", scores)
names = ["Grace", "Ada", "Alan"]
ordered = sorted(names) # returns a new list
print("sorted:", ordered, "names unchanged:", names)
frozen = (1, 2, 3)
try:
frozen.append(4)
except AttributeError as err:
print("tuple:", err)
sort returned None and changed scores to [12, 31, 58, 90]
sorted: ['Ada', 'Alan', 'Grace'] names unchanged: ['Grace', 'Ada', 'Alan']
tuple: 'tuple' object has no attribute 'append'
This code runs but gives a wrong answer on purpose.
def add_tag(tag, tags=[]): # the default list is made once, when def runs
tags.append(tag)
return tags
print(add_tag("a"))
print(add_tag("b")) # expected ['b']
['a']
['a', 'b']
- Verdict: native. Any Python function can change globals, its arguments and the outside world, and nothing in the signature says so. The library marks the difference by name and result:
list.sortchanges the list and returnsNone, andsortedreturns a new list. Tuples, frozensets and frozen dataclasses cannot change, so passing them is safe. - The wrong block uses a list as a default value. The list is made once, when
defruns, so each call that uses the default appends to the same list. The usual fix istags=Noneandif tags is None: tags = []in the body.
#include <iostream>
#include <map>
#include <string>
#include <vector>
class Squares {
public:
long get(long n) const { // const: callers see no change
++lookups_; // mutable: a change that callers cannot observe through the value
auto it = cache_.find(n);
if (it != cache_.end()) return it->second;
return cache_[n] = n * n;
}
int lookups() const { return lookups_; }
private:
mutable std::map<long, long> cache_;
mutable int lookups_ = 0;
};
void append_total(std::vector<int>& xs) { // a non-const reference: xs changes
int t = 0;
for (int x : xs) t += x;
xs.push_back(t);
}
int main() {
const Squares sq;
std::cout << sq.get(12) << ' ' << sq.get(12) << ", lookups " << sq.lookups() << '\n';
std::vector<int> xs{1, 2, 3};
append_total(xs);
for (std::size_t i = 0; i < xs.size(); ++i) std::cout << (i ? " " : "") << xs[i];
std::cout << '\n';
}
144 144, lookups 2
1 2 3 6
- Verdict: native. A
constmember function promises not to change the object, and aconstreference parameter promises not to change the argument. Amutablemember is the exception, for state that callers cannot observe, such as a cache and a counter. A non-constreference parameter, as inappend_total, shows that the function changes the caller's data. Since C++17, the operands of<<are evaluated from left to right, solookups()sees both calls ofget.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;
public class Main {
static void addAll(List<String> target, String... items) { // changes its argument
Collections.addAll(target, items);
}
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("Ada"));
List<String> view = Collections.unmodifiableList(names); // a read-only view
List<String> copy = List.copyOf(names); // an immutable copy
addAll(names, "Alan", "Grace");
System.out.println("view " + view + ", copy " + copy);
try {
view.add("Edsger");
} catch (UnsupportedOperationException e) {
System.out.println("the view rejects add");
}
// Streams are lazy: the peek runs only when a terminal operation pulls items.
Stream<Integer> s = Stream.of(1, 2, 3).peek(x -> System.out.println("peek " + x));
System.out.println("no terminal operation yet");
System.out.println("sum " + s.mapToInt(Integer::intValue).sum());
long n = List.of(1, 2, 3).stream().peek(x -> System.out.println("count peek " + x)).count();
System.out.println("count " + n + " (the count came from the list size)");
}
}
view [Ada, Alan, Grace], copy [Ada]
the view rejects add
no terminal operation yet
peek 1
peek 2
peek 3
sum 6
count 3 (the count came from the list size)
- Verdict: native. A method can change any object that it can reach.
Collections.unmodifiableListgives a read-only view: the view rejectsadd, but it shows the changes that other code makes to the list behind it.List.copyOfmakes an immutable copy that does not change. Streams are lazy, so apeekruns only when a terminal operation pulls items, andcountcan return the size of the source and skip the pipeline, so thepeekbefore it does not run.
#include <stdio.h>
#define MAX(a, b) ((a) > (b) ? (a) : (b)) /* a macro copies its arguments */
static int next_id(void) {
static int id = 0; /* keeps its value between calls */
return ++id;
}
static void scale(int *xs, int n, int k) { /* writes through the pointer */
for (int i = 0; i < n; i++)
xs[i] *= k;
}
int main(void) {
int a = next_id(); /* one call per statement: the order is clear */
int b = next_id();
printf("ids %d %d\n", a, b);
int xs[] = {1, 2, 3};
scale(xs, 3, 10);
printf("scaled %d %d %d\n", xs[0], xs[1], xs[2]);
int before = next_id();
int m = MAX(0, next_id()); /* next_id() runs twice */
printf("last id %d, then MAX(0, next_id()) gave %d\n", before, m);
return 0;
}
ids 1 2
scaled 10 20 30
last id 3, then MAX(0, next_id()) gave 5
- Verdict: native. A
staticlocal variable keeps its value between calls, sonext_idreturns a new number each time. A function that takes a pointer can write through it; aconstpointer parameter promises that it does not. The last line shows a macro trap:MAX(0, next_id())putsnext_id()in the text twice, so it runs twice and skips the id 4. The?:operator has a sequence point after its first operand, so this case is defined; a macro that uses an argument twice in one unsequenced expression, such asSQUARE(i++), is undefined behavior.
int calls = 0;
int[] data = [1, 2, 3];
var doubled = data.Select(x => { calls++; return x * 2; }); // deferred: nothing runs yet
Console.WriteLine($"after Select: {calls} calls");
Console.WriteLine($"sum {doubled.Sum()}, then {calls} calls");
Console.WriteLine($"max {doubled.Max()}, then {calls} calls"); // the query runs again
var list = doubled.ToList(); // run once and keep the results
Console.WriteLine($"list [{string.Join(", ", list)}], then {calls} calls");
var p = new Point(1, 2);
var q = p with { X = 5 }; // a record makes a changed copy
Console.WriteLine($"{p} {q}");
record Point(int X, int Y);
after Select: 0 calls
sum 12, then 3 calls
max 6, then 6 calls
list [2, 4, 6], then 9 calls
Point { X = 1, Y = 2 } Point { X = 5, Y = 2 }
- Verdict: native. C# allows effects anywhere. A LINQ query is deferred:
Selectstores the lambda, and each enumeration runs it again, soSum,MaxandToListeach run the lambda three times.ToListorToArrayruns the query once and keeps the results. Records and thewithexpression make changed copies, andreadonlyfields andinitproperties prevent writes after construction.[Pure]documents a method as pure, and the compiler does not check it.
const scores = [58, 12, 90, 31];
const copy = scores.toSorted((a, b) => a - b); // ES2023: returns a new array
console.log("toSorted:", copy, "original:", scores);
const same = scores.sort((a, b) => a - b); // sorts in place and returns the same array
console.log("sort:", same, "same object:", same === scores);
const user = Object.freeze({ name: "Ada", tags: ["math"] });
user.name = "Alan"; // ignored outside strict mode
user.tags.push("poet"); // freeze is shallow
console.log(user);
let calls = 0;
const doubled = [1, 2, 3].map((x) => { calls++; return x * 2; });
console.log(doubled, "callback ran", calls, "times");
toSorted: [ 12, 31, 58, 90 ] original: [ 58, 12, 90, 31 ]
sort: [ 12, 31, 58, 90 ] same object: true
{ name: 'Ada', tags: [ 'math', 'poet' ] }
[ 2, 4, 6 ] callback ran 3 times
- Verdict: native. JavaScript allows effects anywhere. ECMAScript 2023 added copying versions of the methods that change arrays:
toSorted,toReversed,toSplicedandwith.Object.freezestops changes to the properties of one object, but it is shallow, so the array intagsstill changes. Outside strict mode, a write to a frozen property fails with no error; in strict mode and in modules it throws aTypeError. A callback ofmapshould only compute;forEachis the method for effects.
package main
import "fmt"
type Account struct {
Owner string
Balance int
}
func depositValue(a Account, n int) { a.Balance += n } // changes a copy
func depositPointer(a *Account, n int) { a.Balance += n } // changes the caller's struct
func resetFirst(xs []int) { xs[0] = 0 } // a slice shares its array with the caller
func count(words []string, seen map[string]int) {
for _, w := range words {
seen[w]++ // a map is a reference to shared data
}
}
func main() {
acc := Account{"Ada", 100}
depositValue(acc, 50)
fmt.Println("after depositValue:", acc.Balance)
depositPointer(&acc, 50)
fmt.Println("after depositPointer:", acc.Balance)
xs := []int{7, 8, 9}
resetFirst(xs)
fmt.Println("after resetFirst:", xs)
seen := map[string]int{}
count([]string{"a", "b", "a"}, seen)
fmt.Println("seen:", seen)
}
after depositValue: 100
after depositPointer: 150
after resetFirst: [0 8 9]
seen: map[a:2 b:1]
- Verdict: native. Go passes every argument by value, so a struct parameter is a copy, and
depositValuechanges only its copy. A pointer parameter shows that the function can change the caller's value. Slices and maps are small values that point to shared data, so a function that receives them can change the caller's elements with no pointer in the signature.appendcan also reuse the caller's array when it has spare capacity.
fn total(xs: &[i32]) -> i32 {
xs.iter().sum() // a shared reference: the function can only read
}
fn push_total(xs: &mut Vec<i32>) {
let t = total(xs);
xs.push(t); // &mut in the signature says that the caller's vector changes
}
fn main() {
let mut xs = vec![1, 2, 3];
println!("total {}", total(&xs));
push_total(&mut xs);
println!("after push_total {:?}", xs);
let mut calls = 0;
let doubled: Vec<i32> = xs.iter().map(|x| { calls += 1; x * 2 }).collect();
println!("{:?} after {} calls", doubled, calls);
}
total 6
after push_total [1, 2, 3, 6]
[2, 4, 6, 12] after 4 calls
This code does not compile, on purpose. The error is E0596.
fn push_total(xs: &Vec<i32>) {
let t: i32 = xs.iter().sum();
xs.push(t); // a shared reference does not allow the change
}
fn main() {
let xs = vec![1, 2, 3];
push_total(&xs);
println!("{:?}", xs);
}
- Verdict: native. A function can only change the caller's data when it receives a
&mutreference, and the caller writes&mutat the call, so both sides show the effect. A closure that changes a captured variable, such ascalls, borrows it mutably while the closure lives. The fails block tries to push through a&reference, and the compiler reports E0596. Rust does not track other effects, such as I/O, in types.
Variations and related ideas
- Benign effects. A cache, a log line or a counter of calls changes state but not the results that callers see. C++ marks such members
mutable, and functional programmers still call a memoized function pure. - Idempotence. An operation is idempotent when doing it twice has the same effect as doing it once, such as setting a value or an HTTP
PUT. Idempotent effects make retries safe. - Command-query separation. Bertrand Meyer's rule says that a method should either return a value or change state, not both.
- Effect systems. Languages such as Koka track the effects of each function in its type, and Haskell tracks them through monads such as
IOandState. - Immutability. Immutable values cannot change, so code that shares them has fewer effects to track.
- State. Side effects are the way a program changes its state: the values of its variables, objects and files at a point in the run.
Pitfalls
- Hidden changes to arguments. A function that sorts, appends to or edits an argument surprises a caller that still uses it. Return a new value, or name the function so that the change is clear.
- Shared default values. In Python, a default value such as
[]is made once whendefruns. The documentation says: "the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call."5 - Macros that repeat arguments. A C macro such as
MAX(a, b)evaluates an argument twice, so an argument with a side effect runs twice. - Unspecified order. The order in which C and C++ evaluate the arguments of a function call is unspecified, so
printf("%d %d", next(), next())can print the two values in either order. - Effects in assertions and logs. Code with an effect inside
assert, or inside a log call that is turned off, stops running in the release build. - Effects in lazy pipelines. A lambda with an effect in a stream, a generator or a query runs late, more than once or not at all.
- Shallow protection.
Object.freeze,readonlyfields,finalandconstpointers protect one level. The objects that they refer to can still change.
Cost
Side effects are how a program does useful work, and they cost nothing to write. The cost is in reasoning and in optimization. A compiler cannot remove, reorder or merge calls with effects, so a call in a loop condition runs on every pass. Code with many shared effects needs locks or other synchronization when threads run it. Pure code is easier to test, cache, run in parallel and run again after a failure. Avoiding effects also has a cost: a function that returns a new collection instead of changing one allocates and copies, unless the language uses persistent data structures that share most of their structure.
History
Early languages, from FORTRAN to Algol, were built on assignment, and a function could change global variables freely. Lisp, from 1958, had pure functions in its mathematical core but also assignment with setq and changes to lists with rplaca. Christopher Strachey's lecture notes of 1967, Fundamental Concepts in Programming Languages, used the term referential transparency for expressions that can be replaced by their values. Peter Landin's ISWIM of 1966 and the language ML kept assignment but made it explicit through reference cells.
The lazy functional languages needed another way, because a lazy program evaluates expressions in an order that the programmer does not control. Philip Wadler and Simon Peyton Jones applied monads, from the work of Eugenio Moggi, to I/O, and Haskell 1.3 adopted monadic I/O in 1996. Later work made effects part of more type systems, from the effect systems of the late 1980s to Koka and the effect handlers of OCaml 5 in 2022. Mainstream languages added copying methods, immutable collections and readonly types, which make code with few effects easier to write.
References
- Order of evaluation, C reference, cppreference.com, Definitions, side effects
- Common Function Attributes, Using the GNU Compiler Collection, GCC 15.2, pure and const
- A Gentle Introduction to Haskell, Input/Output, Introduction
- Built-in Types, Python documentation, list.sort
- Compound statements, The Python Language Reference, Function definitions
- Array.prototype.toSorted(), MDN Web Docs, Description
- Package java.util.stream, Java SE 25 API documentation, Side-effects
- Interface Stream, Java SE 25 API documentation, count()
- PureAttribute Class, .NET API documentation, Definition
- Order of evaluation, C++ reference, cppreference.com, Rules
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 QR2VX8 Edit this page History Report an error Markdown