Conceptcore
Value
Also called value, data value, r-value, rvalue, l-value, lvalue, value category, place expression, value expression, first-class value, primitive value, reference value, zero value.
A value is a piece of data that a program computes with, such as 42, "hi" or a list. Expressions give values, variables hold them, and functions take and return them.
- Applies to
- core-languages
Idea
A program computes with data: numbers, text, lists, records and functions. Each such piece of data is a value. An expression such as 3 * 4 + 1 is evaluated to a value, a variable holds a value, and a function takes values as arguments and returns a value. Most other ideas about data, such as types, variables, references and equality, are ideas about values and the places that hold them.
# Evaluation turns an expression into a value.
x = 3 * 4 + 1
print(x, type(x).__name__)
# A value can be stored, passed as an argument and returned.
def double(v):
return v * 2
print(double(x), double("ab"), double([0]))
# Two expressions can give equal values that are different objects.
a = [1, 2]
b = [1] + [2]
print(a == b, a is b)
# On the left of = the name means a location; on the right it means the value in it.
count = 0
count = count + 1
print(count)
# Functions are values too, so a list can hold them.
steps = [abs, str, len]
print([f(-5) if f is not len else f("value") for f in steps])
13 int
26 abab [0, 0]
True False
1
[5, '-5', 5]
3 * 4 + 1 gives the value 13, whose type is int. The function double accepts an int, a str and a list, because * is defined for each of them. The lists a and b have equal values but are two objects. In count = count + 1, the name count on the right means the value that the variable holds, and the same name on the left means the variable itself. The last line stores three functions in a list and calls each of them, so functions are values as well.
How it works
Values and types. "The members of a type are the values of that type"1. The Go specification says that "A type determines a set of values together with operations and methods specific to those values"2. So 13 is a value of int, "abab" is a value of str, and the operations that a program can apply to a value depend on its type. See type.
Location and contents. Wikipedia says that "In languages with assignable variables, it becomes necessary to distinguish between the r-value (or contents) and the l-value (or location) of a variable"1. The names come from the two sides of an assignment. In x = y + 1, the left side must name a place that can hold a value, and the right side must give a value. The language references classify expressions in this way:
- C: "Every expression belongs to one of three value categories: lvalue, non-lvalue object (rvalue), and function designator"3. A "modifiable lvalue is any lvalue expression of complete, non-array type which is not const-qualified"3, so a
constvariable and an array are lvalues that an assignment cannot change. - C++: "Each C++ expression (an operator with its operands, a literal, a variable name, etc.) is characterized by two independent properties: a type and a value category"4. The three primary categories are prvalue, xvalue and lvalue4. An xvalue, such as the result of
std::move(x), names an object whose resources can be moved. - Rust: "Expressions are divided into two main categories: place expressions and value expressions"5, and "A place expression is an expression that represents a memory location"5. Local variables, dereferences, field references and index expressions are place expressions5.
Values and objects. In many languages, a value lives in an object, and the object also has an identity. Python says that "Every object has an identity, a type and a value"6, and that "The value of some objects can change"6. Two lists can have equal values and be different objects, which is the difference between == and is. See equality and identity.
Primitive values and reference values. Java has "two kinds of data values that can be stored in variables, passed as arguments, returned by methods, and operated on"7: primitive values, such as an int, and reference values. "The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object"7. C# puts the line between types: "A variable of a value type contains an instance of the type. This behavior differs from a variable of a reference type, which contains a reference to an instance of the type"8. In JavaScript, "a primitive (primitive value, primitive data type) is data that is not an object and has no methods or properties"9, and "All primitives are immutable"9. When an assignment copies a reference value, the two variables refer to one object. See pointers and references.
Default values. Some languages give a value to every variable that has no initializer. In Go, each element "is set to the zero value for its type: false for booleans, 0 for numeric types, "" for strings, and nil for pointers, functions"2, and for some other types. Java and C# give default values to fields, and C# default(T) gives the default value of a type. C gives no value to a local variable without an initializer, and a read of it gives an indeterminate value. The page Default value has the details.
First-class values. A value is first class when the language lets a program use it in every usual way. Wikipedia says that a first-class citizen "is an entity which supports all the operations generally available to other entities. These operations typically include being passed as an argument, returned from a function, and assigned to a variable"10. Numbers are first class in all the core languages. Functions are first class in Python, JavaScript, Go, Rust and C#, and C and C++ pass them through function pointers and function objects. See higher-order functions.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | TypeScript works with the values of JavaScript, and a literal type such as "on" or 42 describes exactly one value. The compiler erases the types, so the values at run time are JavaScript values. No example file exists. |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | In Kotlin every value is an object in the language, and the compiler stores values of types such as Int and Boolean as JVM primitives where it can. A nullable type such as Int? also holds null. No example file exists because kotlinc is not installed. |
| SQL | Native | Each column of a row holds a value of the column type, and NULL marks a missing value. An expression in a query computes a value for each row. No example file exists. |
| Bash | Idiom | Each Bash variable holds a string, and an indexed or associative array holds strings. Arithmetic expansion reads strings as integers. No example file exists. |
| PowerShell | Native | Each PowerShell value is a .NET object, and the pipeline passes objects from one command to the next. No example file exists because pwsh is not installed. |
| HTML | Idiom | HTML attribute values and text content are strings. Some attributes, such as the value attribute of an input element, hold the value of a form field. |
| CSS | Idiom | Each CSS property takes values of given types, such as lengths, percentages and colors, and the browser computes a value of each property for each element. |
| Regular expressions | Does not apply | A regular expression matches text. The pattern language has no values of its own, although a match gives strings to the host language. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | every value is an object with an identity, a type and a value; == and is |
| JavaScript | native | seven primitive types and objects; primitives compare by value and objects by identity |
| TypeScript | native | the values of JavaScript; literal types such as "on" and 42 describe single values |
| Java | native | primitive values and reference values; null; boxing of primitives |
| Kotlin | native | all values are objects in the language; the compiler stores many of them as JVM primitives |
| C# | native | value types (struct, enum, record struct) and reference types; boxing; default |
| Go | native | values of each type, zero values, and pointer, slice and map values that refer to shared data |
| Rust | native | place expressions and value expressions; move and Copy |
| C | native | lvalues, modifiable lvalues and rvalues; struct values copy on assignment |
| C++ | native | lvalue, xvalue and prvalue; copy and move |
| Bash | idiom | each variable holds a string; arrays hold strings; arithmetic reads strings as integers |
| PowerShell | native | each value is a .NET object, and the pipeline passes objects |
| SQL | native | each column holds values of its type, and NULL marks a missing value |
| Regex | n/a | a pattern matches text; it has no values of its own |
| HTML | idiom | attribute values and text content are strings |
| CSS | idiom | each property takes values of given types, such as lengths, percentages and colors |
Every general-purpose language works with values, so the verdict is native for all of them except Bash, in which all values are strings. The languages differ in where a value lives, in whether an assignment copies the value or a reference to it, and in which kinds of value are first class.
The example files show these differences. Python shows that a list keeps its identity when its value changes, and that += on an int makes a new object. JavaScript shows the result of typeof for each kind of value, and compares primitives by value and objects by identity. Java shows that a method can change the object that a reference value points to but not the variable of the caller, and shows null and boxing. C# copies a struct and shares a class, and shows that a boxed copy does not change. Go shows zero values, the copy of a struct, and a slice that shares its array. Rust shows place expressions, a move and a copy. C shows lvalues, a const lvalue, struct copy and a compound literal. C++ prints the value category of six expressions.
# Every object has an identity, a type and a value.
n = 1000
print(type(n).__name__, n, id(n) == id(n))
# The value of a list can change; its identity and type stay the same.
xs = [1, 2]
before = id(xs)
xs.append(3)
print(xs, id(xs) == before)
# An int value cannot change: += makes a new object and rebinds the name.
k = 10
first = id(k)
k += 1
print(k, id(k) == first)
# == compares values, and is compares identities.
a = [1, 2, 3]
b = list(a)
print(a == b, a is b)
# A tuple is immutable, but the value of a list inside it can still change.
t = (1, [2])
t[1].append(3)
print(t)
# None, True and functions are values that a variable can hold.
values = [None, True, len, 2.5, "s", b"b"]
print([type(v).__name__ for v in values])
int 1000 True
[1, 2, 3] True
11 False
True False
(1, [2, 3])
['NoneType', 'bool', 'builtin_function_or_method', 'float', 'str', 'bytes']
- Verdict: native. Every value is an object with an identity, a type and a value.
appendchanges the value of a list and keeps its identity, but+=on anintmakes a new object and rebinds the name.==compares values andiscompares identities. A tuple is immutable, but the list inside it can still change.None,Trueand functions are values like any other.
#include <print>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
// decltype((e)) gives T& for an lvalue, T&& for an xvalue and T for a prvalue.
template <typename T>
constexpr const char* category() {
if constexpr (std::is_lvalue_reference_v<T>) {
return "lvalue";
} else if constexpr (std::is_rvalue_reference_v<T>) {
return "xvalue";
} else {
return "prvalue";
}
}
#define CATEGORY(...) category<decltype((__VA_ARGS__))>()
int main() {
int x = 1;
std::string s = "text";
std::vector<int> v{1, 2};
std::println("{} {} {} {}", CATEGORY(x), CATEGORY(x + 1), CATEGORY(42), CATEGORY(std::move(x)));
std::println("{} {} {}", CATEGORY(v[0]), CATEGORY(std::string("a")), CATEGORY("literal"));
// Moving from s transfers its value to t, and s is left in a valid but unspecified state.
std::string t = std::move(s);
std::println("{}", t);
// A copy has its own value.
std::vector<int> w = v;
w[0] = 9;
std::println("{} {}", v[0], w[0]);
}
lvalue prvalue prvalue xvalue
lvalue prvalue lvalue
text
1 9
- Verdict: native.
decltype((e))shows the value category of each expression: a variable, an element and a string literal are lvalues,x + 1,42and a temporarystd::stringare prvalues, andstd::move(x)is an xvalue. Moving a string transfers its value to another variable. A copy of a vector is an independent value.
import java.util.ArrayList;
import java.util.List;
public class Main {
static void change(int n, List<String> list) {
n = 99;
list.add("added");
list = new ArrayList<>();
list.add("lost");
}
public static void main(String[] args) {
// A primitive value is the number itself; a reference value points to an object.
int n = 1;
List<String> list = new ArrayList<>(List.of("a"));
change(n, list);
System.out.println(n + " " + list);
// Copying a reference value gives two references to one object.
int[] a = {1, 2};
int[] b = a;
b[0] = 9;
System.out.println(a[0] + " " + (a == b));
// == on references compares identity; equals compares the values.
String s1 = new String("java");
String s2 = new String("java");
System.out.println((s1 == s2) + " " + s1.equals(s2));
// The null reference refers to no object.
String none = null;
System.out.println(none == null);
try {
System.out.println(none.length());
} catch (NullPointerException e) {
System.out.println("NullPointerException");
}
// A primitive value boxes into an object, and the box unboxes to the value.
Object boxed = 42;
int back = (Integer) boxed;
System.out.println(boxed.getClass().getSimpleName() + " " + back);
}
}
1 [a, added]
9 true
false true
true
NullPointerException
Integer 42
- Verdict: native. A method gets copies of the values of its arguments: it cannot change the caller's
intor the caller's variable, but it can change the object that a reference value points to. Two array variables can hold one reference.==on twoStringobjects compares references, andequalscompares text. Thenullreference refers to no object.42boxes into anIntegerand unboxes back.
#include <stdio.h>
struct point {
int x, y;
};
int main(void) {
/* x is an lvalue: it has an address and can be assigned. x + 1 is not an lvalue. */
int x = 5;
int *p = &x;
*p = 6;
printf("%d\n", x);
/* A const object is an lvalue, but not a modifiable lvalue. */
const int limit = 10;
printf("%d %d\n", limit, *&limit);
/* Assignment of a struct copies the value of all its members. */
struct point a = {1, 2};
struct point b = a;
b.x = 10;
printf("%d %d\n", a.x, b.x);
/* A compound literal makes an unnamed object, which is an lvalue. */
int *q = (int[]){7, 8, 9};
q[0] = 70;
printf("%d %d\n", q[0], q[2]);
/* An array is not a modifiable lvalue, so it cannot be assigned, but its elements can. */
int arr[3] = {0};
arr[1] = 4;
printf("%d %zu\n", arr[1], sizeof arr / sizeof arr[0]);
return 0;
}
6
10 10
1 10
70 9
4 3
- Verdict: native.
xis an lvalue, so&xgives its address and*p = 6changes it. Aconstobject is an lvalue but not a modifiable lvalue. Assignment copies all members of a struct. A compound literal makes an unnamed object that is an lvalue. An array cannot be assigned, but its elements can.
// A struct variable holds the value; a class variable holds a reference.
var p1 = new PointS(1, 2);
var p2 = p1;
p2.X = 10;
var c1 = new PointC { X = 1 };
var c2 = c1;
c2.X = 10;
Console.WriteLine($"{p1.X} {p2.X} {c1.X} {c2.X}");
// Boxing copies a value into an object; changes to the copy do not reach the box.
object box = p1;
p1.X = 5;
Console.WriteLine($"{((PointS)box).X} {p1.X}");
// Each type has a default value.
Console.WriteLine($"{default(int)} {default(bool)} {default(PointS).X} {default(string) ?? "null"}");
// A record compares by value; a class compares by reference by default.
Console.WriteLine($"{new Money(5, "EUR") == new Money(5, "EUR")} {new PointC { X = 1 } == new PointC { X = 1 }}");
// A lambda is a value of a delegate type.
Func<int, int> square = v => v * v;
Console.WriteLine(square(7));
struct PointS(int x, int y)
{
public int X = x;
public int Y = y;
}
class PointC
{
public int X;
}
record Money(decimal Amount, string Currency);
1 10 10 10
1 5
0 False 0 null
True False
49
- Verdict: native. A
structvariable holds the value, sop2 = p1copies it, and aclassvariable holds a reference, soc2 = c1shares the object. Boxing copies astructinto an object, and a later change to the variable does not reach the box.defaultgives the default value of each type. Records compare by value and classes by reference.
// A primitive is not an object and has no own properties; typeof tells the kinds apart.
const vals = [42, "hi", true, null, undefined, 10n, Symbol("s"), {}, [], () => 1];
console.log(vals.map((v) => typeof v).join(" "));
// Primitives are immutable: a string method returns a new string.
const s = "value";
const t = s.toUpperCase();
console.log(s, t);
// Primitives compare by value, objects compare by identity.
console.log("ab" === "a" + "b", [1] === [1], { a: 1 } === { a: 1 });
// Object.is differs from === for NaN and -0.
console.log(NaN === NaN, Object.is(NaN, NaN), 0 === -0, Object.is(0, -0));
// An assignment of an object copies the reference, so both names see the change.
const p = { x: 1 };
const q = p;
q.x = 2;
console.log(p.x);
// A function is a value: it can be stored, passed and returned.
const twice = (f) => (v) => f(f(v));
console.log(twice((v) => v + 3)(1));
number string boolean object undefined bigint symbol object object function
value VALUE
true false false
false true true false
2
7
- Verdict: native.
typeofgives the kind of each value, and it says"object"fornull, an object and an array. String methods return new strings, because primitives are immutable. Primitives compare by value, so"ab" === "a" + "b", and objects compare by identity, so[1] === [1]is false.Object.istreatsNaNas equal to itself and0as different from-0. An assignment of an object copies the reference.
package main
import "fmt"
type Point struct{ X, Y int }
func main() {
// A variable with no initializer holds the zero value of its type.
var i int
var s string
var p *Point
var m map[string]int
fmt.Printf("%d %q %v %v\n", i, s, p == nil, m == nil)
// Assignment of a struct copies the value.
a := Point{1, 2}
b := a
b.X = 10
fmt.Println(a, b, a == Point{1, 2})
// A slice value refers to an underlying array, so a copy of the slice shares it.
xs := []int{1, 2, 3}
ys := xs
ys[0] = 9
fmt.Println(xs, ys)
// A pointer value refers to a variable.
q := &a
q.Y = 20
fmt.Println(a)
// Functions are values.
add := func(x, y int) int { return x + y }
apply := func(f func(int, int) int) int { return f(3, 4) }
fmt.Println(apply(add))
}
0 "" true true
{1 2} {10 2} true
[9 2 3] [9 2 3]
{1 20}
7
- Verdict: native. A variable without an initializer holds the zero value of its type. Assignment copies a struct, and
==compares struct values. A slice value refers to an array, so a copy of the slice shares the elements. A pointer value refers to a variable, and a change through it shows in that variable. Functions are values that can be passed as arguments.
fn main() {
// A value expression gives a value; a place expression names a location.
let mut x = 5;
x = x + 1;
let r = &x;
println!("{} {}", x, *r);
// Moving a String transfers the value; the old place can no longer be read.
let s = String::from("text");
let t = s;
println!("{t}");
// Copy types are copied instead: both places keep a value.
let a = 7;
let b = a;
println!("{a} {b}");
// A temporary value lives until the end of the statement.
let len = String::from("temporary").len();
println!("{len}");
// A field and an index are place expressions too.
let mut point = (1, 2);
point.0 = 10;
let mut arr = [0; 3];
arr[1] = 4;
println!("{:?} {:?}", point, arr);
// Functions and closures are values.
let ops: [fn(i32) -> i32; 2] = [|v| v + 1, |v| v * 10];
println!("{:?}", ops.iter().map(|f| f(3)).collect::<Vec<_>>());
}
6 6
text
7 7
9
(10, 2) [0, 4, 0]
[4, 30]
- Verdict: native.
xon the left of=and in&xis a place expression.let t = smoves theString, soscannot be used after it, but an integer isCopy, soaandbboth keep a value. A temporaryStringlives until the end of its statement. A tuple field and an array index are place expressions too. Function pointers are values in an array.
Variations and related ideas
- Value semantics and reference semantics. With value semantics, an assignment copies the value, as with a C struct or a Go array. With reference semantics, an assignment copies a reference, as with a Java object or a Python list.
- Mutable and immutable values. An immutable value never changes, so sharing it is safe. See immutability.
- Values and expressions. An expression is text in the program, and a value is what its evaluation gives. See statements and expressions.
- Values and bindings. A binding links a name to a value or to a location that holds a value. See binding.
- Special values.
null,nil,Noneandundefinedmark the absence of a value.NaNis a floating-point value that is not equal to itself.
Pitfalls
- A shared reference that looks like a copy.
b = awith a list, an array or an object makes a second name for one object, so a change throughbshows througha. Copy the value when two independent values are necessary. ==on references. In Java,==on twoStringobjects compares references, so it can befalsefor equal text. Useequals.- Reading an indeterminate value. In C and C++, a local variable without an initializer has no defined value. Initialize every variable.
- A dangling reference to a temporary. In C++, a reference or a
string_viewto a temporary value refers to a destroyed object after the end of the full expression. NaNand-0. In JavaScript,NaN === NaNis false and0 === -0is true.Object.isgives the other answer for both.
Cost
A small value, such as an integer, a float or a Boolean, fits in a register, and an operation on it takes one instruction or a few. A copy of a large value, such as a big struct or an array, costs time in proportion to its size, which is why many languages pass large values by reference. Boxing a primitive value into an object costs an allocation and an indirection, and the garbage collector must later free the box.
History
The distinction between the location and the contents of a variable came with the first languages that had assignment. Wikipedia says that "The notion of l-values and r-values was introduced by Combined Programming Language (CPL)"1. Christopher Strachey gave a set of lectures in 1967 that became the notes Fundamental Concepts in Programming Languages, written "for the International Summer School in Computer Programming at Copenhagen in August 1967"11. According to Wikipedia, the notes "introduced much programming language terminology still in use today"11, including R-value and L-value. Strachey also contrasted values that ALGOL lets a program use freely with values that it restricts: "In ALGOL, a real number may appear in an expression or be assigned to a variable", but a procedure "may only appear in another procedure call"10. This is the source of the terms first-class and second-class.
Later, the move semantics of C++11 added the xvalue, an expiring value whose resources can be reused, and the categories glvalue and prvalue1.
References
- Value (computer science), Wikipedia, Introduction; Assignment, l-values and r-values
- The Go Programming Language Specification, Types; The zero value
- Value categories, C reference, cppreference.com, Introduction; Lvalue expressions; Modifiable lvalue expressions
- Value categories, C++ reference, cppreference.com, Introduction; Primary categories
- Expressions, The Rust Reference, Place expressions and value expressions
- Data model, The Python Language Reference, 3.1 Objects, values and types
- The Java Language Specification, Java SE 25 Edition, Chapter 4, 4.1 The Kinds of Types and Values; 4.3.1 Objects
- Value types, C# language reference, Introduction
- Primitive, MDN Web Docs Glossary, Introduction
- First-class citizen, Wikipedia, Introduction; History
- Fundamental Concepts in Programming Languages, Wikipedia, 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 Z1Y171 Edit this page History Report an error Markdown