Programming Search⌘K

Conceptcore

Constant evaluation

Also called compile-time evaluation, compile-time function execution, constant expression, constexpr, const fn.

The compiler computes the value of an expression while it translates the program, so the value can size an array, label a case or fail the build.

Applies to
core-languages

Idea

A compiler reads a program and translates it. During the translation, it can also compute some values. 60 * 60 * 24 has the same value each time the program runs, so the compiler can compute 86400 once and put the number in the output. This is constant evaluation. The C standard says it in one sentence: "A constant expression can be evaluated during translation rather than runtime, and accordingly may be used in any place that a constant may be."3

The second half of that sentence is the important part. Some places in a program need a value before the program runs. The size of an array that lives in static memory, a case label, the width of a bit field, a template argument in C++ and a const generic argument in Rust all need a value that the compiler knows. A language that can compute such values lets the programmer write ROWS * COLS and not 12.

A computed constant also lets the compiler check a fact about the program. static_assert(sizeof(int) >= 4) in C and C++ stops the build if the condition is false.13 A check of this kind costs nothing at run time and fails before any user runs the program.

The languages differ in how much code the compiler will run. Two positions mark the ends of the range:

  • A fixed set of operators. C, Go, Java and C# allow literals, names of constants and built-in operators. A constant expression cannot call a function that the programmer wrote.36710
  • Ordinary functions, with limits. C++ constexpr functions and Rust const fn functions are ordinary functions that the compiler can also run. A large part of the language is available inside them, and the rest is forbidden.14

The cpp example both-times shows one constexpr function used by a static_assert, an array bound and a call at run time:

constexpr long factorial(int n) {
    long r = 1;
    for (int i = 2; i <= n; ++i) {
        r *= i;
    }
    return r;
}

static_assert(factorial(5) == 120, "5! is 120");

How it works

An interpreter inside the compiler

To evaluate factorial(5) at compile time, the compiler must run the function. It does not run machine code. It interprets the program in its own internal form, with its own model of memory. The Rust Reference says that a const function called from a const context "is interpreted by the compiler at compile time".4

This interpreter must give the answer that the target machine would give. Rust says so directly: "The interpretation happens in the environment of the compilation target and not the host. So usize is 32 bits if you are compiling against a 32 bit system".4 C requires that a floating expression evaluated during translation has at least the range and precision of the execution environment.3

The interpreter also checks each step. A processor executes a signed overflow or an access out of bounds and continues, and the result is undefined behavior in C and C++. The compiler's interpreter sees the operation and stops. In C++, an operation "that would have undefined behavior" in the core language makes the expression not a core constant expression.1 In Rust, out of bounds indexing and overflow "are compiler errors if the value must be evaluated at compile time".4 So in a constant context, a C++ compiler reports undefined behavior of the core language as an error. See Undefined behavior.

Contexts that require a constant

Each language names the places that need a constant. In Rust, a const context is one of these: the length of an array type, the length in an array repeat expression, the initializer of a constant, a static or an enum discriminant, a const generic argument, and a const block.4 "Expressions in const contexts are always evaluated at compile time."4

Outside these contexts, the rules are different. In Rust, constant expressions elsewhere "may be, but are not guaranteed to be, evaluated at compile time".4 A const fn called from ordinary code "behaves the same as if it did not have the const qualifier".4 C++ has the same split. A constexpr function call produces the same result as a call to a function that is not constexpr, except that it can also appear in a constant expression.1

So constexpr and const fn grant permission. They do not force evaluation at compile time. The place of the call decides. An optimizing compiler can also fold a constant expression in ordinary code, but that is an optimization, and the program cannot depend on it.

Forcing evaluation

C++20 added consteval.1 A function declared consteval is an immediate function, and each call of it must produce a constant.1 The cpp example consteval-runtime passes argc to such a function, and the compiler rejects it. A constexpr variable also forces evaluation, because its initializer must be a constant expression.1

A function sometimes needs two implementations: one that the compiler can interpret and a faster one for run time. C++ has if consteval for this. If the statement is evaluated in a context that is manifestly constant-evaluated, the first branch runs. Otherwise the else branch runs.1

Static assertions

A static assertion takes a constant condition and a message. C11 added static assertions, and C23 made static_assert a keyword and added a form with one argument.3 In C the condition is an integer constant expression.3 In C++ the condition is a constant expression converted to bool. If it is false, the program is ill-formed, and the diagnostic should include the message.1 Rust has no special keyword. A panic during constant evaluation is a compile error, so const _: () = assert!(...); does the same work. The rust example assert shows it.

In languages

LanguageVerdictNote
PythonAbsentPython has no compile-time evaluation step in the language. A module-level name in capital letters is a constant by convention only. Alternative: Compute the value once at import time and assign it to a module-level name.
C++Native
JavaNative
CNative
C#Native
JavaScriptAbsentConst makes a binding that cannot be reassigned, and the value is computed at run time. Alternative: Compute the value once when the module loads.
TypeScriptIdiomMembers of a const enum can use only constant enum expressions, and the compiler inlines them at each use; no example file because Node.js type stripping does not support enums. Alternative: A const binding of JavaScript computed at run time.
GoNative
RustNative
KotlinNativeConst val declares a compile-time constant of a primitive type or String that the compiler inlines; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLDoes not applyA query has no user-defined compile-time computation.
BashAbsentThe shell has no compile step in which to evaluate expressions.
PowerShellAbsentThe language has no constant expressions that a compiler evaluates before the script runs.
HTMLDoes not applyMarkup has no expressions to evaluate.
CSSDoes not applyStyle rules have no compile step.
Regular expressionsDoes not applyA pattern has no expressions to evaluate.
Language Verdict Form
C++ native constexpr variables and functions, consteval, if consteval, static_assert
Rust native const items, const fn, const blocks, assert! in a const item
C native operators on constants; C23 constexpr objects and static_assert; no constant functions
Go native exact untyped constants, iota, len of constants; no constant functions
Java native constant expressions and constant variables; no method calls
C# native const fields and locals; no method calls
Kotlin native const val of a primitive type or String
TypeScript idiom const enum members, inlined by the compiler
JavaScript absent const is a binding computed at run time
Python absent capital names are constants by convention
PowerShell absent no compile-time constants
Bash absent no compile-time constants
SQL n/a no user-defined compile-time computation
Regex n/a no expressions
HTML/CSS n/a no compile step

C++ allows a large part of the language in a constant evaluation. It can even allocate memory with new, if the storage is deallocated within the same evaluation.1 The cpp example heap builds a std::vector inside a constant evaluation. The list of forbidden operations includes a call to a function that is not constexpr, an operation with undefined behavior in the core language, reinterpret_cast, a throw expression, an asm declaration and a goto statement.1 For undefined behavior in the library, the standard leaves it unspecified whether the expression is a core constant expression.1 The standard also allows a constexpr function for which no call is a constant expression: "It is possible to write a constexpr function for which no invocation satisfies the requirements of a core constant expression."1

Rust grew const fn step by step. Rust 1.31 allowed "a minimal subset of operations" in a const fn: arithmetic on integers, construction of arrays, structs, enums and tuples, calls to other const fn functions, index expressions and field access.5 The Reference lists loop and while as constant expressions.4 It does not list for, because a for loop calls trait methods. The rust example for-loop shows the error. A const function cannot be async.4

C had constant expressions from C89: "Constant expressions shall not contain assignment, increment, decrement, function-call, or comma operators".163 C23 added the constexpr storage class for objects.3 Such an object "has its value permanently fixed at translation-time".3 Its initializer must give a value that the type represents exactly. The standard example marks constexpr unsigned int minusOne = -1; as a constraint violation and constexpr double onethird = 1.0/3.0; as a possible constraint violation.3 constexpr applies to objects only. A function definition can have only extern or static as a storage class.3

Go constants are exact. "Numeric constants represent exact values of arbitrary precision and do not overflow."6 A compiler must represent integer constants with at least 256 bits.6 A constant can be untyped, and it takes a type only when the program uses it. At that point the value must fit: int32(1) << 33 is illegal.6 "Constant expressions may contain only constant operands and are evaluated at compile time."6 The built-in len gives a constant for a string constant or an array without function calls, but a call to a function of the program is never constant.6

Java defines a constant expression as "an expression denoting a value of primitive type or a String that does not complete abruptly", built from literals, casts, most operators, the conditional operator and the names of constant variables.7 A constant variable is "a final variable of primitive type or type String that is initialized with a constant expression".8 Method calls are not in the list, so Math.max(10, 20) is not a constant expression even though its result never changes. String constant expressions are interned, and constant expressions are used as case labels.7

C# constants "can be numbers, Boolean values, strings, or a null reference".10 "A constant expression is an expression that the compiler can fully evaluate at compile time."10 An interpolated string can be a constant "if all expressions used are also constant strings".10 The compiler evaluates constant expressions in a checked context, so an overflow is a compile-time error.11 A value that is known only at run time, such as the current time, goes in a static readonly field.10

Kotlin marks a compile-time constant with const val. It must be a top-level property or a member of an object declaration or a companion object, its value must be of type String or a primitive type, and it cannot have a custom getter. "Compile-time constants are inlined at compile time, so each reference is replaced with its actual value."12 No Kotlin example runs on this page, because kotlinc is not installed on the machine that recorded the examples.

TypeScript compiles const enum declarations away. "Const enums can only use constant enum expressions and unlike regular enums they are completely removed during compilation. Const enum members are inlined at use sites."13 No TypeScript example runs, because the examples run under Node.js type stripping, which rejects enums. JavaScript const is not a compile-time constant. It "creates an immutable reference to a value" and the value is computed when the declaration runs.14 Python has no constant evaluation in the language. PEP 8 says that "Constants are usually defined on a module level and written in all capital letters".15

#include <array>
#include <iostream>

constexpr long factorial(int n) {
    long r = 1;
    for (int i = 2; i <= n; ++i) {
        r *= i;
    }
    return r;
}

static_assert(factorial(5) == 120, "5! is 120");

int main(int argc, char**) {
    constexpr long f10 = factorial(10);
    std::array<int, factorial(4)> slots{};
    std::cout << "factorial(10) = " << f10 << "\n";
    std::cout << "slots: " << slots.size() << "\n";
    int n = argc + 5;
    std::cout << "factorial(" << n << ") = " << factorial(n) << "\n";
}
Output
factorial(10) = 3628800
slots: 24
factorial(6) = 720

One constexpr function serves three uses. The compiler evaluates factorial(5) for the static_assert, factorial(10) for a constexpr variable and factorial(4) for an array bound. The last call takes a value that exists only at run time, so the program evaluates it at run time.

This code does not compile, on purpose.

#include <iostream>

consteval int square(int x) {
    return x * x;
}

int main(int argc, char**) {
    std::cout << square(4) << "\n";
    std::cout << square(argc) << "\n";
}

A consteval function is an immediate function. Each call must produce a constant. square(4) is acceptable, but square(argc) depends on a run-time value, so the compiler rejects the program.

This code does not compile, on purpose.

#include <iostream>

constexpr int factorial(int n) {
    int r = 1;
    for (int i = 2; i <= n; ++i) {
        r *= i;
    }
    return r;
}

int main() {
    constexpr int f13 = factorial(13);
    std::cout << f13 << "\n";
}

13! is 6227020800 and does not fit in a 32-bit int. Signed overflow is undefined behavior, and an expression with undefined behavior is not a core constant expression. The compiler must diagnose it here. The same call at run time compiles and has undefined behavior.

This code does not compile, on purpose.

constexpr int depth(int n) {
    return n == 0 ? 0 : 1 + depth(n - 1);
}

int main() {
    constexpr int d = depth(2000);
    return d == 2000 ? 0 : 1;
}

The function is correct, but the evaluation is too deep. The compilers stop at a fixed number of nested calls, and the program fails to compile. A loop in place of the recursion compiles.

#include <iostream>
#include <numeric>
#include <vector>

constexpr int sum_of_squares(int n) {
    std::vector<int> v;
    for (int i = 1; i <= n; ++i) {
        v.push_back(i * i);
    }
    return std::accumulate(v.begin(), v.end(), 0);
}

static_assert(sum_of_squares(4) == 30);

int main() {
    constexpr int s = sum_of_squares(10);
    std::cout << "sum of squares 1..10 = " << s << "\n";
}
Output
sum of squares 1..10 = 385

A constant evaluation can allocate memory with new if it frees the memory before it ends. Here std::vector allocates and frees inside sum_of_squares, and only the int result leaves the evaluation.

  • Verdict: native. constexpr marks variables and functions that can take part in constant expressions, consteval marks functions that must, and static_assert checks a constant condition at compile time.
  • A constexpr function is not always evaluated at compile time. It is evaluated at compile time when a constant expression needs its value.
  • An evaluation that reaches undefined behavior in the core language, a call to a function that is not constexpr, a reinterpret_cast, a throw expression or a goto statement is not a constant expression.
JavaGitHub
public class Main {
    static final int SMALL = 1;
    static final int LARGE = SMALL * 100;
    static final String PREFIX = "user-";

    static String size(int n) {
        switch (n) {
            case SMALL:
                return "small";
            case LARGE:
                return "large";
            default:
                return "other";
        }
    }

    public static void main(String[] args) {
        System.out.println(size(1) + " " + size(100) + " " + size(7));
        String id = "user-42";
        String constant = PREFIX + "42";
        String suffix = "42";
        String computed = PREFIX + suffix;
        System.out.println("constant == id: " + (constant == id));
        System.out.println("computed == id: " + (computed == id));
        System.out.println("computed.equals(id): " + computed.equals(id));
    }
}
Output
small large other
constant == id: true
computed == id: false
computed.equals(id): true

SMALL and LARGE are constant variables: final, of a primitive type or String, and initialized with a constant expression. So they can be case labels. PREFIX + "42" is a constant expression, and the compiler interns it, so it is the same object as the literal "user-42". suffix is not final, so PREFIX + suffix is computed at run time and gives a different object. Compare strings with equals, not ==.

This code does not compile, on purpose.

public class Main {
    static final int LIMIT = Math.max(10, 20);

    public static void main(String[] args) {
        switch (args.length) {
            case LIMIT:
                System.out.println("limit");
                break;
            default:
                System.out.println("other");
        }
    }
}

LIMIT is final, but its initializer calls a method. A method call is never part of a constant expression, so LIMIT is not a constant variable and cannot be a case label.

This code raises ArithmeticException, on purpose.

public class Main {
    public static void main(String[] args) {
        final int zero = 0;
        final int ratio = 1 / zero;
        System.out.println(ratio);
    }
}

1 / zero uses only constants, but it would complete abruptly. A constant expression must not complete abruptly, so this one is not constant. The compiler accepts the program, and the division throws at run time.

  • Verdict: native. A constant expression has a primitive or String value and uses literals, operators, casts and the names of constant variables. It has no method calls and no user code.
  • The compiler copies the value of a constant variable into each class that uses it. If a library changes the value, a class that was compiled against the old value keeps the old value until it is compiled again.
#include <stdio.h>

constexpr int rows = 3;
constexpr int cols = 4;
constexpr unsigned int all_bits = -1U;

static_assert(rows * cols == 12, "the grid has 12 cells");
static_assert(sizeof(int) >= 2);

int main(void) {
    int grid[rows * cols] = {0};
    printf("cells: %zu\n", sizeof grid / sizeof grid[0]);
    printf("all_bits: %u\n", all_bits);
    return 0;
}
Output
cells: 12
all_bits: 4294967295

C23 adds constexpr for objects and makes static_assert a keyword. A constexpr object is a named constant, so rows * cols is an integer constant expression and grid is an ordinary array, not a variable length array. static_assert with one argument has no message.

This code does not compile, on purpose.

#include <stdio.h>

constexpr unsigned int minus_one = -1;

int main(void) {
    printf("%u\n", minus_one);
    return 0;
}

The value -1 cannot be represented in unsigned int. A plain const unsigned int accepts this conversion and gets the maximum value. A constexpr object must hold its initializer exactly, so the compiler rejects the program. -1U is the portable spelling.

This code does not compile, on purpose.

#include <stdio.h>

constexpr int square(int x) {
    return x * x;
}

int main(void) {
    printf("%d\n", square(4));
    return 0;
}

C has no constexpr functions. A function definition can have only extern or static as a storage class. The C constant expression also forbids function calls, so a C program computes a constant with a macro or by hand.

  • Verdict: native. C23 has constexpr objects and static_assert. Constant expressions are a fixed set of operators on constants, with no function calls.
  • A const object is not a named constant in C. After const int n = 4;, the declaration int a[n]; inside a function declares a variable length array.
using System;

class Program
{
    const int Rows = 3;
    const int Cols = 4;
    const int Cells = Rows * Cols;
    const string Name = "grid";
    const string Label = $"{Name} cells";
    static readonly long Started = DateTime.Now.Ticks;

    static string Kind(int n) => n switch
    {
        Cells => "full",
        0 => "empty",
        _ => "partial",
    };

    static void Main()
    {
        Console.WriteLine($"{Label}: {Cells}");
        Console.WriteLine($"{Kind(12)} {Kind(0)} {Kind(5)}");
        Console.WriteLine($"readonly set at run time: {Started > 0}");
    }
}
Output
grid cells: 12
full empty partial
readonly set at run time: True

const values are computed by the compiler, so Cells can be a pattern in a switch. An interpolated string whose parts are constant strings is also a constant. A value that needs a call at run time, such as the time, must be a static readonly field.

This code does not compile, on purpose.

using System;

class Program
{
    const int Big = int.MaxValue + 1;

    static void Main()
    {
        Console.WriteLine(Big);
    }
}

The compiler evaluates constant expressions in a checked context. int.MaxValue + 1 overflows, so the program does not compile. The same addition on variables wraps at run time in the default unchecked context.

This code does not compile, on purpose.

using System;

class Program
{
    const int Larger = Math.Max(10, 20);

    static void Main()
    {
        Console.WriteLine(Larger);
    }
}

Math.Max is a method call, and the compiler does not run methods to compute a constant. The program does not compile.

  • Verdict: native. A const holds a number, a Boolean value, a string or null, and the compiler evaluates its initializer. The language has no compile-time functions and no static assertion.
  • Other assemblies copy the value of a public const when they compile. If the value changes, those assemblies must be compiled again to see it.
package main

import "fmt"

const Huge = 1 << 100
const Four int8 = Huge >> 98

type Weekday int

const (
	Sunday Weekday = iota
	Monday
	Tuesday
)

var table [len("abcd")]int

func main() {
	fmt.Println("Four:", Four)
	fmt.Println("Huge >> 90:", Huge>>90)
	fmt.Println("Tuesday:", Tuesday)
	fmt.Println("table:", len(table))
}
Output
Four: 4
Huge >> 90: 1024
Tuesday: 2
table: 4

Huge is 2 to the power 100. It has no type, and the compiler keeps it as an exact value. Constants do not overflow. Only Four and the printed shift must fit in a machine type. iota numbers the constants in a group. len of a string constant is a constant, so it can size an array.

This code does not compile, on purpose.

package main

import "fmt"

const Big = int32(1) << 33

func main() {
	fmt.Println(Big)
}

A typed constant must fit in its type. int32(1) << 33 overflows int32, and the compiler reports the error.

This code does not compile, on purpose.

package main

import "fmt"

func square(x int) int {
	return x * x
}

const Nine = square(3)

func main() {
	fmt.Println(Nine)
}

A Go constant expression has only constant operands and a few built-in functions, such as len. A call to a user function is never constant, even when the function is pure. Use a var that the program initializes at run time.

  • Verdict: native. Constants are exact values that the compiler computes. The language has no compile-time functions, and no static assertion keyword.
  • A constant with no type takes a type when the program uses it. The value must then fit in that type.
RustGitHub
const fn factorial(n: u64) -> u64 {
    let mut r = 1;
    let mut i = 2;
    while i <= n {
        r *= i;
        i += 1;
    }
    r
}

const F10: u64 = factorial(10);
const _: () = assert!(factorial(5) == 120);

fn main() {
    let slots = [0u8; factorial(4) as usize];
    println!("F10 = {F10}");
    println!("slots: {}", slots.len());
    let n = std::env::args().count() as u64 + 5;
    println!("factorial({n}) = {}", factorial(n));
}
Output
F10 = 3628800
slots: 24
factorial(6) = 720

The initializer of a const item and the length of an array are const contexts, and the compiler evaluates them. assert! in a const item runs at compile time. The call with n is outside a const context, so it is an ordinary call.

This code does not compile, on purpose.

const fn factorial(n: u64) -> u64 {
    let mut r = 1;
    let mut i = 2;
    while i <= n {
        r *= i;
        i += 1;
    }
    r
}

const _: () = assert!(factorial(5) == 100, "5! is 120, not 100");

fn main() {
    println!("unreachable");
}

A panic during constant evaluation is a compile error. So assert! in an unnamed const item is the Rust form of a static assertion.

This code does not compile, on purpose.

const fn factorial(n: u32) -> u32 {
    let mut r = 1;
    let mut i = 2;
    while i <= n {
        r *= i;
        i += 1;
    }
    r
}

const F13: u32 = factorial(13);

fn main() {
    println!("{F13}");
}

13! does not fit in u32. In a const context, overflow is a compile error (E0080), and the compiler shows the call that failed.

This code does not compile, on purpose.

const fn sum(xs: &[u32]) -> u32 {
    let mut total = 0;
    for x in xs {
        total += *x;
    }
    total
}

fn main() {
    println!("{}", sum(&[1, 2, 3]));
}

A for loop calls trait methods of IntoIterator and Iterator. They are not const functions, so the compiler rejects the loop with error E0015. A while loop with an index compiles.

  • Verdict: native. const fn functions run at compile time in const contexts: const and static initializers, array lengths, enum discriminants, const generic arguments and const blocks.
  • The set of operations allowed in a const fn is smaller than in a normal function, and it has grown since Rust 1.31.
  • Constant folding. An optimizer computes constant subexpressions in ordinary code. The program cannot see whether this happened, and the language does not require it. Constant evaluation in the sense of this page is part of the language and has rules that every compiler follows.
  • Macros. A macro also does work at compile time, but it produces code, not values. C programs that need a constant computed from parts often use a macro, because C has no constant functions. See Syntactic macros.
  • Generics. C++ templates and Rust const generics take constant values as arguments, so the compiler must evaluate them before it can instantiate the code. See Generics.
  • Immutability. const in JavaScript, final in Java and readonly in C# stop a variable from changing after it is set. They do not move the computation to compile time. See Immutability.
  • Precomputed tables. A constant evaluation can fill an array at compile time. The program then reads the table at run time with no setup cost.

Pitfalls

Expecting constexpr to mean compile time

A call to a constexpr function in ordinary code is an ordinary call. Only a constant context forces the compiler to evaluate it.1 Rust has the same rule for const fn.4 If the evaluation at compile time matters, assign the result to a constexpr variable or a Rust const item, or use consteval in C++.

Overflow in a constant

The cpp example overflow computes 13! in a 32-bit int. In a constant context, the compiler finds the overflow and rejects the program. The same call at run time compiles, and its overflow is undefined behavior.1 The C# example overflow and the rust example overflow show the same check. A Go typed constant must fit its type, so the go example overflow also fails to compile.6 This is an advantage of constant evaluation, but only for the values that the compiler evaluates.

Limits of the compiler

A constant evaluation runs inside the compiler, and the compiler has limits. The C++ standard recommends at least 512 recursive constexpr calls and 1 048 576 full-expressions in one core constant expression. These numbers are "only guidelines and do not determine compliance".1 An expression that would exceed the limits of the implementation is not a core constant expression.1 The cpp example depth recurses 2000 times and fails to compile. Write deep computations as loops, and keep the work of a constant evaluation small, because the compiler does it again in each build.

A method call that looks constant

In Java, C# and Go, a call to a library function such as Math.max is never a constant expression, even when the arguments are constants.7106 The java example method-call and the csharp example call fail for this reason. Write the value, or compute it at run time in a static final or static readonly field.

An abrupt completion in Java

A Java constant expression must not complete abruptly.7 1 / zero, where zero is a constant variable with the value 0, is therefore not a constant expression. The compiler accepts it as ordinary code, and the division throws ArithmeticException when it runs. The java example abrupt shows this. Go rejects a constant division by zero at compile time.6

Constants copied into other binaries

The compiler puts the value of a constant into the code that uses it. In Java, a reference to a constant variable "must be resolved at compile time to the value", and a class that was compiled against an old value "will not see any new value for a usage of the field unless they are recompiled".9 The specification calls these "inconstant constants" and recommends "very sparing use of static constant variables".9 C# warns about the same effect for public constants in libraries: other code "needs to be recompiled to see the changes".10 Use a constant only for a value that will not change, and use a static final or static readonly field for a value such as a version number.

Lossy conversion in a C constexpr

const unsigned int x = -1; is valid C and gives the maximum value. With constexpr, the same declaration is a constraint violation, because the value -1 is not representable in unsigned int.3 The c example minus-one shows the error. Write -1U.

Cost

  • Run time. A value computed by the compiler costs nothing when the program runs. The program reads it as a literal.
  • Compile time. The compiler interprets the code, so heavy constant evaluation makes each build slower.
  • Language surface. C++ and Rust split their functions into those that can run at compile time and those that cannot. Each library function must decide whether it is constexpr or const, and a change of that decision can break callers.14
  • Binary coupling. Inlined constants tie compiled clients to the old value, as described under Pitfalls.9

History

  • 1989. The ANSI C standard defined a constant expression as one that "can be evaluated during translation rather than runtime", and it forbade function calls in it.16
  • 2007. Dos Reis, Stroustrup and Maurer proposed generalized constant expressions for C++ in N2235. The paper extended constant expressions to "constant-expression functions" and user-defined literals, to support generic programming, systems programming and library building.2
  • C++11. constexpr and static_assert became keywords.1
  • C11. C added static assertions.3
  • 2018. Rust 1.31 shipped const fn with "a minimal subset of operations".5
  • C++20. C++ added the keyword consteval for immediate functions.1
  • C23. C added constexpr for objects, made static_assert a keyword and added its form with one argument.3

References

  1. N4950, Working Draft, Standard for Programming Language C++ (the C++23 draft), 7.7 [expr.const] paragraphs 5, 15, 18 and 19; 8.5.2 [stmt.if] paragraphs 4 and 5; 9.1 [dcl.pre] paragraph 10; 9.2.6 [dcl.constexpr] paragraphs 1 to 6; Annex B [implimits] paragraph 2, items 2.38 and 2.39; C.2.2 paragraph 3; C.5.2 paragraph 3
  2. Gabriel Dos Reis, Bjarne Stroustrup, Jens Maurer, Generalized Constant Expressions, Revision 5, N2235, 17 April 2007, Abstract; 1 Introduction
  3. N3220, working draft of ISO/IEC 9899:2024 (C23), 6.6 Constant expressions, paragraphs 2, 3, 7 and 8; 6.7.2 Storage-class specifiers, paragraphs 2, 5, 16 and 18 with its example; 6.7.12 Static assertions; 6.9.2 Function definitions, paragraph 4; M.2 Fifth Edition; M.4 Third Edition
  4. The Rust Reference, Constant evaluation, const-eval.intro; const-eval.const-expr.evaluation; const-eval.const-expr.runtime-context; const-eval.const-expr.error; const-eval.const-expr.loop; const-eval.const-context; const-eval.const-fn.const-context; const-eval.const-fn.outside-context; const-eval.const-fn.async
  5. The Rust Core Team, Announcing Rust 1.31 and Rust 2018, The Rust Blog, 6 December 2018, const fn
  6. The Go Programming Language Specification, Constants (including the implementation restriction); Constant expressions; Length and capacity
  7. The Java Language Specification, Java SE 25 Edition, 15.29 Constant Expressions
  8. The Java Language Specification, Java SE 25 Edition, 4.12.4 final Variables (the definition of a constant variable)
  9. The Java Language Specification, Java SE 25 Edition, 13.1 The Form of a Binary; 13.4.9 final Fields and static Constant Variables
  10. C# language reference, The const keyword, the introduction; the paragraph on interpolated strings; the paragraph on readonly
  11. C# language reference, The checked and unchecked statements, the first paragraph; the paragraph on constant expressions
  12. Kotlin documentation, Properties, Compile-time constants
  13. TypeScript Handbook, Enums, const enums
  14. MDN Web Docs, const, Description
  15. PEP 8, Style Guide for Python Code, Constants
  16. Draft of ANSI X3.159-1989, Programming Language C, 3.4 Constant expressions

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/MQEEPJ/text.yaml