Programming Search⌘K

Conceptcore

Declaration

Also called declaration, definition, declaration and definition, forward declaration, prototype, function prototype, extern declaration, tentative definition, one definition rule, ODR, hoisting, declare before use.

A declaration introduces a name and tells the compiler what the name is, such as a variable of a type or a function with a signature. A definition is a declaration that also gives the thing itself.

Applies to
core-languages

Idea

A program uses names, and the compiler or the interpreter must know what each name is. A declaration introduces a name and gives its properties: a variable and its type, a function and its parameters, or a type and its parts. A definition is a declaration that also gives the thing itself: the storage for a variable, the body of a function or the layout of a type. Some languages keep the two apart, so that one file can declare a function and another file can define it. Other languages join them, so that each declaration is also a definition.

class Config:
    name: str  # a declaration only: a name and a type, but no value
    retries: int = 3  # a declaration and a definition: it also gives the value


print(Config.__annotations__)
print(hasattr(Config, "name"), Config.retries)

# def is a statement that runs, so the function exists only after the def has run.
try:
    early()
except NameError as e:
    print("NameError:", e)


def early():
    return "now it exists"


print(early())


# A function body looks up names when it runs, so it can use a function defined below it.
def first():
    return second()


def second():
    return "second"


print(first())
Output
{'name': <class 'str'>, 'retries': <class 'int'>}
False 3
NameError: name 'early' is not defined
now it exists
second

name: str declares a name and a type, but it gives no value, so the class has no attribute name. retries: int = 3 declares the name and also defines it. In Python, def is a statement that runs, so a call before the def fails with NameError. A function body looks up names when it runs, so first can call second, which is defined below it.

How it works

Declaration and definition. "The term "declaration" is frequently contrasted with the term "definition", but meaning and usage varies significantly between languages"1. The C standard gives the exact rule: "A declaration specifies the interpretation and properties of a set of identifiers." A definition is a declaration that, for an object, "causes storage to be reserved for that object", and for a function "includes the function body"2. C++ uses the same split: "Definitions are declarations that fully define the entity introduced by the declaration"3.

What a declaration gives. A declaration usually gives some of these properties:

  • The kind of thing: a variable, a constant, a function, a type, a module or a label.
  • The type, or the signature of a function. Some languages infer the type from the value, with var, auto or :=.
  • The scope, which is the part of the program where the name is valid. See lexical scope.
  • The storage and the linkage: static, extern, const, final and similar words.

Declare before use, or any order. C reads a file from top to bottom, so a function must have a declaration before the first call. A prototype such as int sum(int a, int b); gives the declaration, and the definition can come later or in another file. Other languages let the program use a name before its declaration:

  • In Java, "The scope of a declaration of a member m declared in or inherited by a class or interface C ... is the entire body of C"4. A local variable is different: its scope "is the rest of the block, starting with the declaration's own initializer"4.
  • In Go, the scope of a name declared at top level "is the package block"5, so the order of the top-level declarations does not matter.
  • In Rust, "Items may be defined in any order"6, and this is also true for an item inside a block.
  • In C#, "You can declare a local function before or after the statements that call it"7.
  • In JavaScript, hoisting lets code use some names before their declarations. MDN describes it as "the process whereby the interpreter appears to move the declaration of functions, variables, classes, or imports to the top of their scope, prior to execution of the code"8. A function declaration is hoisted with its body. A var is hoisted, but its value is not, so it reads as undefined. A class or a let cannot be read before its declaration runs.

Declarations in Python. Python has no declaration of a variable. An assignment makes the name. The global statement "causes the listed identifiers to be interpreted as globals", and the nonlocal statement "causes the listed identifiers to refer to names previously bound in nonlocal scopes"9. An annotation such as total: int declares a type for tools and for __annotations__, but when the right side is not present, no value is bound9. def and class are definitions that run as statements.

Declarations in Go. "A declaration binds a non-blank identifier to a constant, type, type parameter, variable, function, label, or package. Every identifier in a program must be declared"5. Go has two forms of type declaration. "A type definition creates a new, distinct type with the same underlying type and operations as the given type", and "An alias declaration binds an identifier to the given type"5.

One definition. A program can declare a name many times, but it must define it only once. C++ requires "One and only one definition of every non-inline function or variable that is odr-used" in the entire program, and "The compiler is not required to diagnose this violation"3. C has a special case: a file-scope declaration of an object without an initializer and without extern is a tentative definition. If the file has no other definition, the declaration acts as a definition with a zero value2.

Declaration without definition. A declaration can name a thing that another unit gives. In C and C++, an extern declaration or a prototype in a header file names a variable or a function that another file defines, and the linker joins them. In Rust, "External blocks provide declarations of items that are not defined in the current crate"10. In C#, "A partial member has one declaring declaration and often one implementing declaration. The declaring declaration doesn't include a body"11.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CNative
C#Native
JavaScriptNative
TypeScriptNativeTypeScript has the declarations of JavaScript and adds type annotations, and declare and .d.ts files give declarations without a definition for code that is written in JavaScript. No example file exists.
GoNative
RustNative
KotlinNativeKotlin declares names with val, var and fun, lateinit declares a property that gets its value later, and expect and actual split a declaration from its definition in multiplatform code. No example file exists because kotlinc is not installed.
SQLNativeCREATE TABLE, CREATE VIEW and the other CREATE statements declare schema objects, and procedural SQL such as PL/pgSQL has a DECLARE section for variables. No example file exists.
BashNativeBash declares variables with declare, local and readonly, and a function definition makes a function. A variable needs no declaration. No example file exists.
PowerShellNativePowerShell declares functions with function and parameters with param, and a cast such as [int]$n declares a typed variable. A variable needs no declaration. No example file exists because pwsh is not installed.
HTMLIdiomAn id attribute declares a name for an element, and links, label elements and scripts refer to the element by that name.
CSSNativeThe @property rule declares a custom property with a syntax, an initial value and inherits: true or false. In CSS, the word declaration also means a pair of a property and a value.
Regular expressionsIdiomA named group such as (?<year>...) declares a name for a group, and a backreference or the program uses the name later.
Language Verdict Mechanism
Python native def, class, global, nonlocal, annotations; no declaration of a variable
JavaScript native function, class, var, let, const; hoisting
TypeScript native as JavaScript; type annotations; declare and .d.ts files
Java native members in any order; local variables before use; var
Kotlin native val, var, fun; lateinit; expect and actual
C# native members in any order; local functions; partial members; out var
Go native var, const, type, func, :=; top level in any order
Rust native items in any order; let; extern blocks
C native declare before use; prototypes; extern; tentative definitions
C++ native forward declarations; one definition rule; inline variables
Bash native declare, local, readonly; function definitions
PowerShell native function, param; typed variables such as [int]$n
SQL native CREATE statements declare schema objects; DECLARE in procedural SQL
Regex idiom named groups declare a name for a group
HTML idiom the id attribute declares a name that links and labels refer to
CSS native @property declares a custom property with a type and an initial value

Every general-purpose language has declarations. The verdict is native for all of them, and the languages differ in three things: whether a variable must be declared, whether a name can be used before its declaration, and whether a declaration can exist without a definition.

The example files show these differences. Python shows global, nonlocal, an annotation without a value and a conditional def. JavaScript shows the hoisting of a function, a var, a class and a function expression. Java uses a method before its declaration and declares a local variable that the compiler checks on each path. C# calls a local function before its declaration and joins the two declarations of a partial method. Go puts top-level declarations after main and shows iota and the two forms of type declaration. Rust uses items before their declarations and calls the C function abs through an extern block. C declares a variable and a function before it defines them and shows a tentative definition. C++ shows a forward declaration of a type and the declaration and definition of a static data member.

PythonGitHub
count = 0


def bump():
    global count  # a declaration: count in this function is the module name
    count += 1


def counter():
    n = 0

    def step():
        nonlocal n  # a declaration: n is the name of the enclosing function
        n += 1
        return n

    return step


bump()
bump()
print("count =", count)
s = counter()
s()
print("step() =", s())

total: int  # an annotation alone declares a type but binds no value
print("total is bound:", "total" in globals())

if count > 1:
    def mode():
        return "many"
else:
    def mode():
        return "few"
print("mode() =", mode())
Output
count = 2
step() = 2
total is bound: False
mode() = many
  • Verdict: native. Python has no declaration of a variable, and an assignment makes the name. global and nonlocal are declarations that tell the compiler where a name is bound. An annotation without a value declares a type but binds nothing, so total is not in globals(). def runs as a statement, so a condition can choose which function to define.
#include <iostream>
#include <string>

struct Node;                   // a forward declaration: an incomplete type
int twice(int x);              // a function declaration
extern int counter;            // a variable declaration

struct List {
    Node* head = nullptr;      // a pointer to an incomplete type is valid
    static int made;           // a declaration of a static data member
    static inline int open = 0;  // an inline variable: also a definition
};
int List::made = 0;            // the definition of the static data member

auto greet(const std::string& n) { return "hi " + n; }  // the return type is deduced

int main() {
    std::cout << "twice(4) = " << twice(4) << "\n";
    counter += 1;
    List::made += 1;
    std::cout << "counter = " << counter << ", made = " << List::made
              << ", open = " << List::open << "\n";
    std::cout << greet("ada") << "\n";
}

int counter = 41;              // the definition of counter
int twice(int x) { return 2 * x; }
Output
twice(4) = 8
counter = 42, made = 1, open = 0
hi ada
  • Verdict: native. struct Node; is a forward declaration, so List can hold a pointer to it. static int made; declares a static data member, and the definition is outside the class. static inline int open is a declaration and a definition. counter and twice are declared before main and defined after it. auto deduces the return type of greet from its body.
JavaGitHub
import java.util.List;

public class Main {
    // A method can be used before its declaration in the class body.
    static int twice(int x) { return add(x, x); }
    static int add(int a, int b) { return a + b; }

    // A field declaration with an initializer.
    static final List<String> NAMES = List.of("a", "b");

    public static void main(String[] args) {
        System.out.println("twice(4) = " + twice(4));

        // A local variable must be declared before it is used.
        int y;
        if (args.length == 0) { y = 1; } else { y = 2; }
        System.out.println("y = " + y);  // definitely assigned on each path

        var list = NAMES;  // var: the compiler infers the declared type
        System.out.println("list = " + list + ", size " + list.size());

        // A local class declaration.
        record Pair(int a, int b) { int sum() { return a + b; } }
        System.out.println("sum = " + new Pair(2, 3).sum());
    }
}
Output
twice(4) = 8
y = 1
list = [a, b], size 2
sum = 5
  • Verdict: native. A method is in scope in the whole class body, so twice can call add, which comes after it. A local variable must be declared before use, and the compiler checks that it has a value on each path. var declares a local variable with an inferred type. A record can be declared inside a method.
#include <stdio.h>

extern int total;          /* a declaration: the object is defined below */
int sum(int a, int b);     /* a function declaration (a prototype) */
struct node;               /* an incomplete type: a declaration only */

int tentative;             /* a tentative definition */
int tentative;             /* another one is valid, and they name one object */

struct list { struct node *head; int size; };

int main(void) {
    printf("sum(2, 3) = %d\n", sum(2, 3));
    total += 5;
    printf("total = %d\n", total);
    printf("tentative = %d\n", tentative);
    struct list l = { NULL, 0 };
    printf("l.size = %d\n", l.size);
    return 0;
}

int total = 10;                           /* the definition of total */
int sum(int a, int b) { return a + b; }   /* the definition of sum */
Output
sum(2, 3) = 5
total = 15
tentative = 0
l.size = 0
  • Verdict: native. extern int total; and the prototype of sum are declarations, and the definitions come after main. struct node; declares an incomplete type, and a pointer to it is valid. Two declarations int tentative; are tentative definitions of one object, which has the value 0.
// A local function can be called before its declaration in the block.
Console.WriteLine($"Square(5) = {Square(5)}");
static int Square(int x) => x * x;

// An out variable is declared in the call.
if (int.TryParse("42", out var n))
{
    Console.WriteLine($"n = {n}");
}

var p = new Shape();
Console.WriteLine($"p.Name() = {p.Name()}");

// A partial class has two declarations, and the compiler joins them.
partial class Shape
{
    public partial string Name();  // a declaration without a body
}

partial class Shape
{
    public partial string Name() => "shape";  // the definition
}
Output
Square(5) = 25
n = 42
p.Name() = shape
  • Verdict: native. A local function can be called before its declaration. out var declares a variable inside a call. A partial method has a declaring declaration without a body and an implementing declaration with the body, and the compiler joins the two parts of the class.
JavaScriptGitHub
// A function declaration is hoisted with its body, so the call before it works.
console.log("area(2) =", area(2));
function area(r) { return 3 * r * r; }

// A var declaration is hoisted, but its value is not, so x is undefined here.
console.log("x before =", x);
var x = 5;
console.log("x after =", x);

// A class declaration is hoisted but stays in the temporal dead zone.
try { new Point(); } catch (e) { console.log(e.name + ":", e.message); }
class Point { constructor() { this.x = 0; } }

// A function expression is a value, so only the var name is hoisted.
try { later(); } catch (e) { console.log(e.name + ":", e.message); }
var later = function () { return 1; };

// A declaration in a block: let is local to the block, var is not.
{ let inner = 1; var outer = 2; }
console.log(typeof inner, typeof outer);
Output
area(2) = 12
x before = undefined
x after = 5
ReferenceError: Cannot access 'Point' before initialization
TypeError: later is not a function
undefined number
  • Verdict: native. A function declaration is hoisted with its body, so the call before it works. A var is hoisted without its value, so it reads as undefined. A class declaration is in the temporal dead zone until it runs. A function expression assigned to a var is not hoisted, so the early call fails with TypeError. let is local to its block, and var is not.
package main

import "fmt"

// Package-level declarations can be in any order, so main can use limit.
func main() {
	fmt.Println("limit =", limit, "double(limit) =", double(limit))

	var z int // a var declaration without a value gives the zero value
	fmt.Println("z =", z)

	n := 3 // a short variable declaration
	fmt.Println("n =", n)

	const (
		Low = iota // iota counts the specs in a const declaration
		Mid
		High
	)
	fmt.Println("Low, Mid, High =", Low, Mid, High)

	var c Celsius = 20
	var a Alias = 7
	fmt.Printf("%T %T\n", c, a)
}

func double(x int) int { return 2 * x }

const limit = 10

type Celsius float64 // a type definition: a new type

type Alias = int // an alias declaration: another name for int
Output
limit = 10 double(limit) = 20
z = 0
n = 3
Low, Mid, High = 0 1 2
main.Celsius int
  • Verdict: native. Top-level declarations can come in any order, so main uses limit and double before they appear. A var without a value gives the zero value. iota numbers the specs of a const declaration. A type definition makes the new type main.Celsius, and an alias declaration makes another name for int.
RustGitHub
// Items can be in any order, so main can use helper and Point.
fn main() {
    println!("helper() = {}", helper());
    let p = Point { x: 1, y: 2 };
    println!("p = ({}, {})", p.x, p.y);

    // A let declaration without a value; the compiler checks each path.
    let y;
    if p.x > 0 { y = "positive"; } else { y = "other"; }
    println!("y = {y}");

    // An item inside a block is visible in the whole block.
    println!("inner() = {}", inner());
    fn inner() -> i32 { 7 }

    // A declaration of a foreign function; the C library gives the definition.
    let a = unsafe { abs(-3) };
    println!("abs(-3) = {a}");
}

unsafe extern "C" {
    fn abs(x: i32) -> i32;
}

fn helper() -> &'static str { "ok" }

struct Point { x: i32, y: i32 }
Output
helper() = ok
p = (1, 2)
y = positive
inner() = 7
abs(-3) = 3
  • Verdict: native. Items can come in any order, also inside a block, so main uses helper, Point and inner before their declarations. A let without a value is valid if each path assigns it. An extern block declares the C function abs, and the C library gives the definition, so the call needs unsafe.
  • Forward declaration. A declaration before the definition lets two functions or two types refer to each other. In C, struct node; declares a type whose parts are not known yet, and a pointer to it is valid.
  • Header files and interface files. "Declarations are often collected into header files"1. A C header, a TypeScript .d.ts file and the declaring part of a C# partial member all give declarations for code that is defined in another place.
  • Implicit declaration. Some languages declare a name when the program first uses it. In FORTRAN, a variable whose name starts with I, J, K, L, M or N is an integer unless a declaration says otherwise. Old C let a program call a function without a declaration and assumed that it returned int.
  • Type inference. var in Java and C#, auto in C++, := in Go and let in Rust declare a variable and let the compiler find its type from the value.
  • Declaration and binding. A declaration usually makes a binding. In Python, the binding comes from an assignment, and a declaration such as global only changes where the binding goes.

Pitfalls

  • A declaration without a definition. A prototype or an extern declaration that has no definition in the program compiles, but the link fails with an undefined reference.
  • Two definitions. Two definitions of one function or variable break the one definition rule. Some cases give a link error, and some give a program that is wrong with no error3.
  • Declarations that do not agree. If one C file declares extern int count; and another defines double count;, the compiler cannot see the problem. Put the declaration in a header file and include the header in the file that defines the name.
  • Hoisting that hides an error. A var that is read before its assignment gives undefined and not an error. Use let and const, which give a ReferenceError.
  • An annotation that looks like a definition. In Python, total: int does not make the name, so a read of total raises NameError.
  • A forward declaration that is too weak. An incomplete type can be used only through a pointer or a reference. The code that reads its fields or makes an object of it needs the full definition.

Cost

A declaration costs nothing at run time in compiled languages. It gives information to the compiler and the linker. The cost is at build time: a C or C++ file that includes many headers makes the compiler read many declarations again for each file, and a forward declaration in place of an include can make the build faster. In Python, a def or a class is a statement that runs, so it costs a little time each time it runs, for example a def inside a loop.

History

The ALGOL 60 report, from the conference in Paris in January 1960, has a section named Declarations. "Declarations serve to define certain properties of the quantities used in the program, and to associate them with identifiers. A declaration of an identifier is valid for one block"12. This joined declarations to the block structure, which most later languages kept.

C made the split between declaration and definition exact, because a C program is compiled one file at a time and joined by a linker. The current C standard still defines a definition as a declaration that reserves storage or gives a function body, and still has tentative definitions2. C++ added the one definition rule3. Later languages such as Java, Go and Rust let a program use a member or an item before its declaration456, and Java "does not require separate declarations and definitions"1.

References

  1. Declaration (computer programming), Wikipedia, Introduction; Declarations and definitions
  2. ISO/IEC 9899:2024 working draft N3220, Programming languages, C, 6.7.1, paragraph 6; 6.9.3, paragraph 2
  3. Definitions and ODR (One Definition Rule), C++ reference, cppreference.com, Introduction; One Definition Rule
  4. The Java Language Specification, Java SE 25 Edition, Chapter 6, 6.3 Scope of a Declaration
  5. The Go Programming Language Specification, Declarations and scope; Type declarations
  6. Items, The Rust Reference, items.decl-order; items.name-resolution
  7. Local functions, C# programming guide, Local function syntax
  8. Hoisting, MDN Web Docs Glossary, Introduction
  9. Simple statements, The Python Language Reference, 7.2.2 Annotated assignment statements; 7.12 The global statement; 7.13 The nonlocal statement
  10. External blocks, The Rust Reference, items.extern.intro
  11. Partial member, C# language reference, Introduction
  12. Revised Report on the Algorithmic Language Algol 60, J. W. Backus and others, edited by Peter Naur, Introduction; 5. Declarations

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