Programming Search⌘K

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);
Output
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

LanguageVerdictNote
PythonIdiom
C++Native
JavaNative
CNative
C#Native
JavaScriptNative
TypeScriptNativeTypeScript 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.
GoNative
RustNative
KotlinNativeKotlin 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.
SQLIdiomA 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.
BashNativeReadonly NAME=value, or declare -r NAME=value, makes a variable that cannot be assigned or unset. No example file exists.
PowerShellNativeSet-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.
HTMLDoes not applyHTML is markup, with no names for values.
CSSIdiomA 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 expressionsDoes not applyA 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

PythonGitHub
from typing import Final

MAX_SIZE: Final = 10
LIMITS: Final = [1, 2]

MAX_SIZE = 11
LIMITS.append(3)
print(MAX_SIZE, LIMITS)
Output
11 [1, 2, 3]
  • Verdict: idiom. Python has no constants. A name in capitals is a constant by convention, and typing.Final marks it for a type checker such as mypy, which reports the line MAX_SIZE = 11 as an error. The interpreter runs the line with no error, and a list behind a Final name 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';
}
Output
9 3
  • Verdict: native. constexpr asks the compiler to compute the value, here with a call to a constexpr function, so kSize can be the size of an array and the operand of static_assert. A const object, such as name, gets its value at run time and cannot change after that.
JavaGitHub
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");
        }
    }
}
Output
10 [Ada] 3
UnsupportedOperationException
  • Verdict: native. static final with a constant expression gives a compile-time constant. A final local can get its value later, once: length is a blank final. final keeps the reference, but the list behind it can change. List.of makes a list that cannot change, and add throws 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;
}
Output
Bob 7 0.2 10
  • Verdict: native. The qualifier const stops writes to an object: rate = 0.3 does not compile. In const char *name, the characters are constant but the pointer is not, so name = "Bob" is fine; char *const makes the pointer constant. A #define macro or an enum gives 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;
    }
}
Output
10
3
  • Verdict: native. const gives a compile-time constant, and its value must be a constant expression. A readonly field 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.
JavaScriptGitHub
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));
Output
0.2 5
false 3 true
  • Verdict: native. const stops a new assignment to the name, but not a change to the object. Object.freeze stops changes to the properties of the object. Reflect.set returns false for the failed write. A plain assignment to a frozen property does nothing outside strict mode, and throws a TypeError in 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)
}
Output
4
1024 1048576 1073741824
true
  • Verdict: native. A Go constant is a value of the compiler, with exact arithmetic: 1 << 100 is too large for any integer type, but Big >> 98 is 4, a value that fits. An untyped constant takes the type of its use, so Big can be a float64. In a const block, iota counts the lines, and a line with no expression repeats the expression before it.
RustGitHub
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);
}
Output
10 86400 2
  • Verdict: native. A const item needs a type, and its value is computed at compile time, so 24 * 60 * 60 costs nothing at run time. A let binding without mut, such as count, is a run-time constant: the value comes from the program, and the compiler rejects a second assignment.
  • 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 100 replaces the text before the compiler runs. It has no type and no scope. A const object or an enum is 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 const array in JavaScript, or a final list 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);
Output
[ '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 = 10 can get a new value anywhere, with no error at run time. Use a type checker with Final, or an Enum.
  • 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 readonly field 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

  1. Constant (computer programming), Wikipedia, Introduction; Use; Dynamically-valued constants; Naming conventions
  2. Constant items, The Rust Reference, items.const.intro; items.const.behavior
  3. The const keyword, C# reference, Introduction
  4. constexpr specifier, cppreference.com (C++), Explanation
  5. The Go Programming Language Specification, Constants; Constant expressions
  6. Chapter 4, Types, Values, and Variables, The Java Language Specification, Java SE 25, 4.12.4 final Variables
  7. readonly, C# reference, Introduction
  8. const, MDN Web Docs, Description
  9. typing, Support for type hints, Python documentation, typing.Final
  10. const type qualifier, cppreference.com (C), Explanation
  11. 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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/NEC2B0/text.yaml