Conceptintro
Constant
Also called constant, named constant, symbolic constant, const, final, readonly, constexpr, val, compile-time constant, run-time constant, read-only variable.
A constant is a name for a value that does not change while the program runs. A compile-time constant has a value that the compiler knows, and a run-time constant gets its value once and keeps it.
- Applies to
- core-languages
Idea
Some values in a program never change: the number of days in a week, a maximum size, a tax rate for this year. A constant gives such a value a name. "In computer programming, a constant is a value that is not altered by the program during normal execution."1 A Variable, in contrast, "is an identifier with a value that can be changed during normal execution"1.
In JavaScript, const declares a constant, and an assignment to it fails:
const DAYS_PER_WEEK = 7;
const weeks = 3;
console.log(weeks * DAYS_PER_WEEK);
try {
DAYS_PER_WEEK = 8;
} catch (e) {
console.log(e.name);
}
console.log(DAYS_PER_WEEK);
21
TypeError
7
The name DAYS_PER_WEEK tells the reader what 7 means, and a change in one place changes every use. "A constant value is defined once and can be referenced many times throughout a program."1
How it works
Why constants help. "Constants are useful for both programmers and compilers: for programmers, they are a form of self-documenting code and allow reasoning about correctness, while for compilers, they allow compile-time and run-time checks that verify that constancy assumptions are not violated"1. A name such as MAX_RETRIES is clearer than the number 3 in many places, which is often called a magic number.
Compile-time constants. The compiler knows the value, because it is a literal or an expression of literals. The compiler can put the value at each use. In Rust, "A constant item is an optionally named constant value which is not associated with a specific memory location in the program"2. In C#, "A constant expression is an expression that the compiler can fully evaluate at compile time"3, and the value of a const must be such an expression. In C++, "The constexpr specifier declares that it is possible to evaluate the value of the entities at compile time"4. Go constants are values of the compiler only: "Numeric constants represent exact values of arbitrary precision and do not overflow"5.
Run-time constants. The value comes from the input or from a computation at run time, but after the first assignment it does not change. "Besides the static constants described above, many procedural languages such as Ada and C++ extend the concept of constantness toward global variables that are created at initialization time, local variables that are automatically created at runtime"1, and parameters. In Java, "A final variable may only be assigned to once"6. In C#, a readonly field gets its value "during the declaration or in a constructor in the same class"7.
A constant name is not a constant object. In most languages, the keyword stops a new assignment to the name. It does not stop a change inside the object that the name refers to. MDN says: "The const declaration creates an immutable reference to a value. It does not mean the value it holds is immutable"8. Java says the same of final: "If a final variable holds a reference to an object, then the state of the object may be changed by operations on the object, but the variable will always refer to the same object."6 For a value that cannot change at all, see Immutability.
How the compiler checks. "Some programming languages make an explicit syntactic distinction between constant and variable symbols, for example considering assignment to a constant to be a syntax error"1. Java, C#, Rust, Go, C and C++ reject the assignment at compile time. JavaScript throws a TypeError when the assignment runs, as the idea example shows. Python has no constants: typing.Final tells a type checker that "Final names cannot be reassigned in any scope"9, but the interpreter does not check it.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Idiom | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | TypeScript has the const of JavaScript, readonly properties and readonly arrays that the compiler checks, and the assertion as const, which makes the literal types of an object or an array read only. No example file exists. |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | Kotlin val declares a name that is assigned once, and const val declares a compile-time constant of a basic type or String at the top level or in an object. No example file exists because kotlinc is not installed. |
| SQL | Idiom | A SQL query writes fixed values as literals. Procedural extensions of database systems can declare constants, and a table can hold values that the program treats as fixed. No example file exists. |
| Bash | Native | Readonly NAME=value, or declare -r NAME=value, makes a variable that cannot be assigned or unset. No example file exists. |
| PowerShell | Native | Set-Variable with the option Constant makes a variable that cannot change or be removed in the session, and the option ReadOnly makes one that can be removed with -Force. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML is markup, with no names for values. |
| CSS | Idiom | A custom property that the style sheet sets once, such as a brand color on the root element, acts as a named constant, but any rule can set it again. No example file exists. |
| Regular expressions | Does not apply | A pattern has literal characters, but no names for fixed values. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | idiom | no constants; a name in capitals such as MAX_SIZE by convention, and typing.Final for a type checker |
| JavaScript | native | const: the name cannot get a new value; the object can still change |
| TypeScript | native | const, and readonly properties and as const for literal types |
| Java | native | final for a variable assigned once; static final with a constant expression for a compile-time constant |
| Kotlin | native | val for a name assigned once, and const val for a compile-time constant |
| C# | native | const for a compile-time constant, readonly for a field set once at run time |
| Go | native | const for compile-time constants of a basic type, typed or untyped |
| Rust | native | const items are inlined at each use; let without mut is a run-time constant |
| C | native | the qualifier const on an object, and #define for a macro |
| C++ | native | const, and constexpr for a value known at compile time |
| Bash | native | readonly NAME=value or declare -r NAME=value |
| PowerShell | native | Set-Variable -Option Constant or -Option ReadOnly |
| SQL | idiom | a query uses literals; procedural extensions declare constants, and a table can hold fixed values |
| Regex | n/a | a pattern has literal characters, but no names for values |
| HTML | n/a | HTML is markup, with no names for values |
| CSS | idiom | a custom property that the style sheet never changes acts as a named constant |
C. "Any attempt to modify an object whose type is const-qualified results in undefined behavior."10 A cast can remove const from a pointer, and the compiler then does not stop the write, but the program is wrong.
Bash. The option -r of declare makes names read only: "These names cannot then be assigned values by subsequent assignment statements or unset."11
from typing import Final
MAX_SIZE: Final = 10
LIMITS: Final = [1, 2]
MAX_SIZE = 11
LIMITS.append(3)
print(MAX_SIZE, LIMITS)
11 [1, 2, 3]
- Verdict: idiom. Python has no constants. A name in capitals is a constant by convention, and
typing.Finalmarks it for a type checker such as mypy, which reports the lineMAX_SIZE = 11as an error. The interpreter runs the line with no error, and a list behind aFinalname can still change.
#include <array>
#include <iostream>
#include <string>
constexpr int square(int n) { return n * n; }
constexpr int kSize = square(3);
int main() {
std::array<int, kSize> cells{};
const std::string name = "Ada";
static_assert(kSize == 9);
std::cout << cells.size() << ' ' << name.size() << '\n';
}
9 3
- Verdict: native.
constexprasks the compiler to compute the value, here with a call to aconstexprfunction, sokSizecan be the size of an array and the operand ofstatic_assert. Aconstobject, such asname, gets its value at run time and cannot change after that.
import java.util.ArrayList;
import java.util.List;
public class Main {
static final int MAX_SIZE = 10;
public static void main(String[] args) {
final List<String> names = new ArrayList<>();
names.add("Ada");
final int length;
length = names.get(0).length();
System.out.println(MAX_SIZE + " " + names + " " + length);
List<String> fixed = List.of("Ada");
try {
fixed.add("Bob");
} catch (UnsupportedOperationException e) {
System.out.println("UnsupportedOperationException");
}
}
}
10 [Ada] 3
UnsupportedOperationException
- Verdict: native.
static finalwith a constant expression gives a compile-time constant. Afinallocal can get its value later, once:lengthis a blank final.finalkeeps the reference, but the list behind it can change.List.ofmakes a list that cannot change, andaddthrows an exception.
#include <stdio.h>
#define MAX_SIZE 10
enum { DAYS_PER_WEEK = 7 };
int main(void) {
const double rate = 0.2;
const char *name = "Ada";
name = "Bob";
int counts[MAX_SIZE] = {0};
printf("%s %d %.1f %zu\n", name, DAYS_PER_WEEK, rate, sizeof counts / sizeof counts[0]);
return 0;
}
Bob 7 0.2 10
- Verdict: native. The qualifier
conststops writes to an object:rate = 0.3does not compile. Inconst char *name, the characters are constant but the pointer is not, soname = "Bob"is fine;char *constmakes the pointer constant. A#definemacro or anenumgives a constant that can size an array.
using System;
Console.WriteLine(Limits.MaxSize);
var a = new Account(3);
Console.WriteLine(a.Id);
static class Limits
{
public const int MaxSize = 10;
}
class Account
{
public readonly int Id;
public Account(int id)
{
Id = id;
}
}
10
3
- Verdict: native.
constgives a compile-time constant, and its value must be a constant expression. Areadonlyfield gets its value in the declaration or in a constructor, so each object can have a different value, and an assignment after the constructor does not compile.
const RATE = 0.2;
const config = { retries: 3 };
config.retries = 5;
console.log(RATE, config.retries);
const frozen = Object.freeze({ retries: 3 });
console.log(Reflect.set(frozen, "retries", 5), frozen.retries, Object.isFrozen(frozen));
0.2 5
false 3 true
- Verdict: native.
conststops a new assignment to the name, but not a change to the object.Object.freezestops changes to the properties of the object.Reflect.setreturnsfalsefor the failed write. A plain assignment to a frozen property does nothing outside strict mode, and throws aTypeErrorin strict mode.
package main
import "fmt"
const Big = 1 << 100
const (
KB = 1 << (10 * (iota + 1))
MB
GB
)
func main() {
fmt.Println(Big >> 98)
fmt.Println(KB, MB, GB)
var f float64 = Big
fmt.Println(f > 1e30)
}
4
1024 1048576 1073741824
true
- Verdict: native. A Go constant is a value of the compiler, with exact arithmetic:
1 << 100is too large for any integer type, butBig >> 98is 4, a value that fits. An untyped constant takes the type of its use, soBigcan be afloat64. In aconstblock,iotacounts the lines, and a line with no expression repeats the expression before it.
const MAX_SIZE: usize = 10;
const SECONDS_PER_DAY: u32 = 24 * 60 * 60;
fn main() {
let names = vec!["Ada", "Bob"];
let count = names.len();
println!("{} {} {}", MAX_SIZE, SECONDS_PER_DAY, count);
}
10 86400 2
- Verdict: native. A
constitem needs a type, and its value is computed at compile time, so24 * 60 * 60costs nothing at run time. Aletbinding withoutmut, such ascount, is a run-time constant: the value comes from the program, and the compiler rejects a second assignment.
Variations and related ideas
- Naming. "Naming conventions for constants vary. Some simply name them as they would any other variable. Others use capitals and underscores for constants in a way similar to their traditional use for symbolic macros, such as SOME_CONSTANT."1
- Macros. A C macro such as
#define MAX 100replaces the text before the compiler runs. It has no type and no scope. Aconstobject or anenumis often better. - Enumerations. An enumeration gives a set of related constants one type, such as the days of the week.
- Immutable objects. "A constant data structure or object is referred to as "immutable" in object-oriented parlance."1 See Immutability.
Pitfalls
- The object behind a constant name can change. A
constarray in JavaScript, or afinallist in Java, still accepts new elements:
This code runs but gives a wrong answer on purpose.
const COLORS = ["red", "green"];
COLORS.push("blue");
console.log(COLORS);
const FROZEN = Object.freeze(["red", "green"]);
try {
FROZEN.push("blue");
} catch (e) {
console.log(e.name);
}
console.log(FROZEN.length);
[ 'red', 'green', 'blue' ]
TypeError
2
Object.freeze stops changes to the array itself. The elements are strings, which cannot change, so the array is now fully constant.
- A Python constant is only a name.
MAX_SIZE = 10can get a new value anywhere, with no error at run time. Use a type checker withFinal, or anEnum. - A compile-time constant is copied into other code. The C# reference says: "Don't create a constant to represent information that you expect to change over time."3 The reason: "because compilers propagate constants, other code compiled with your libraries needs to be recompiled to see the changes"3. Use a
readonlyfield for a value that can change between versions, and configuration for a value such as a price or a URL.
Cost
A compile-time constant costs nothing at run time: the compiler puts the value at each use, and it can compute expressions of constants once. A run-time constant costs the same as a variable. The compiler can use the fact that it does not change, for example to keep it in a register.
History
Constants are as old as high-level languages, and the idea of a constant at run time has its own history: Wikipedia cites a 1995 article in SIGPLAN Notices, "Dynamically-Valued Constants: An Underused Language Feature", for the constants that Ada and C++ make at run time1. Ada has untyped constants such as pi : constant := 3.1415926535;, "with the untyped variant being implicitly converted to the appropriate type upon each use"1.
References
- Constant (computer programming), Wikipedia, Introduction; Use; Dynamically-valued constants; Naming conventions
- Constant items, The Rust Reference, items.const.intro; items.const.behavior
- The const keyword, C# reference, Introduction
- constexpr specifier, cppreference.com (C++), Explanation
- The Go Programming Language Specification, Constants; Constant expressions
- Chapter 4, Types, Values, and Variables, The Java Language Specification, Java SE 25, 4.12.4 final Variables
- readonly, C# reference, Introduction
- const, MDN Web Docs, Description
- typing, Support for type hints, Python documentation, typing.Final
- const type qualifier, cppreference.com (C), Explanation
- Bash Builtin Commands, Bash Reference Manual, declare -r; readonly
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 NEC2B0 Edit this page History Report an error Markdown