Programming Search⌘K

Conceptcore

Identifier

Also called identifier, identifiers, name, names, symbol, variable name, keyword, reserved word, contextual keyword, soft keyword, raw identifier, verbatim identifier, exported identifier, blank identifier, name mangling.

An identifier is a name that a program gives to a variable, function, type or other entity. The lexer reads it as one token, and the rules of the language decide which characters it can hold.

Applies to
core-languages

Idea

A program names the things it makes: variables, functions, types, fields and modules. Each name is an identifier. The lexer reads an identifier as one token, and each language has a rule for its form, usually a letter or _ followed by letters, digits and _. Some words have the form of a name but are reserved by the language. These are keywords.

import keyword

# An identifier is a name that the program chooses. The lexer checks its form,
# and a keyword has the form of a name but is reserved by the language.
for name in ["count", "_tmp", "café", "π", "x2", "2x", "my-var", "class", "match"]:
    if not name.isidentifier():
        verdict = "not a name"
    elif keyword.iskeyword(name):
        verdict = "keyword, not usable"
    elif keyword.issoftkeyword(name):
        verdict = "soft keyword, usable as a name"
    else:
        verdict = "name"
    print(f"{name:8} {verdict}")

# Names are case-sensitive, and Python compares them after NFKC normalization,
# so the ligature fi (one character) and the two letters f and i are one name.
ns = {}
exec(chr(0xFB01) + "le = 3\nFile = 4", ns)
print(sorted(k for k in ns if not k.startswith("__")))
Output
count    name
_tmp     name
café     name
π        name
x2       name
2x       not a name
my-var   not a name
class    keyword, not usable
match    soft keyword, usable as a name
['File', 'file']

isidentifier checks only the form, so 2x and my-var fail and class passes. class is a keyword, so a program cannot use it as a name. match is a soft keyword: it has a special meaning only at the start of a match statement, and it is a normal name elsewhere. The last line shows two more rules. Names are case-sensitive, so file and File are two names, and Python normalizes names, so the ligature fi followed by le is the name file.

How it works

The form. Most languages use the same base rule. Go states it as "An identifier is a sequence of one or more letters and digits. The first character in an identifier must be a letter", and Go counts _ as a letter1. A digit cannot be first, so the lexer can tell x2 from the number 2. A character such as - cannot be in a name, so my-var is my - var. Java also allows $, which "should be used only in mechanically generated source code"2, and JavaScript allows $ freely3.

Keywords. A keyword has the form of a name, but the grammar gives it a meaning, so the language excludes it from names. The Java grammar defines an identifier as "IdentifierChars but not a ReservedKeyword or BooleanLiteral or NullLiteral"2. A contextual keyword is a keyword only in some places. In Java, var, record, sealed, permits and yield cannot name a type but can name a variable2. In C++, final, import, module and override "are used explicitly in a certain context rather than being regular identifiers"4. Contextual keywords let a language add a keyword without breaking old programs that use the word as a name. Python calls them soft keywords5.

Escapes for keywords. Some languages let a program use a keyword as a name with a prefix. In C#, "An identifier with an @ prefix is called a verbatim identifier", so @class is a variable named class6. In Rust, r#match is a raw identifier7. This matters when code calls a library that is written in another language or in an older edition, where the word was not a keyword.

Unicode. Most modern languages allow letters of all scripts, so größe and π are valid names. The common rule comes from Unicode Standard Annex 31, which gives the character classes XID_Start and XID_Continue for the first and the other characters of a name8. The same visible text can have more than one encoding, for example é as one character or as e and a combining accent. Python converts all names "into the normalization form NFKC while parsing"5. In Rust, "Identifiers are normalized using Normalization Form C (NFC)", and "Two identifiers are equal if their NFC forms are equal"7. JavaScript and Go do not normalize names, so the two encodings give two names, or no name at all.

Unicode escapes. In JavaScript, Java and C#, a Unicode escape can spell a character of a name. MDN gives the example that 你好 and its escaped form "are the same identifiers"326.

Names with a meaning. In some languages, the form of a name changes what it means:

  • In Go, a name is exported from its package when its first character is "a Unicode uppercase letter (Unicode character category Lu)"1. The blank identifier _ "does not introduce a binding and thus is not declared"1.
  • In Python, a name in a class body that starts with two underscores is mangled with the class name, "to help avoid name clashes between “private” attributes of base and derived classes"5.
  • In JavaScript, a name that starts with # is a private field of a class3.
  • In C, the identifiers "that begin with an underscore followed by a capital letter or by another underscore" are reserved for the implementation, and a program that declares one has undefined behavior9.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CNative
C#Native
JavaScriptNative
TypeScriptNativeTypeScript uses the identifier rules of JavaScript and adds contextual keywords such as type, keyof and satisfies, which are still valid names. No example file exists.
GoNative
RustNative
KotlinNativeKotlin allows Unicode letters in names, has hard, soft and modifier keywords, and lets a name in backticks hold a keyword or spaces, but no example file exists because kotlinc is not installed.
SQLNativeSQL has regular identifiers, which the database folds to one case, and delimited identifiers in double quotes, which keep their case and can be keywords. No example file exists.
BashNativeA Bash variable name is letters, digits and _ and does not start with a digit, and the shell is case-sensitive. No example file exists.
PowerShellNativePowerShell variables start with $, the form ${...} allows any characters in a name, and names are not case-sensitive, but no example file exists because pwsh is not installed.
HTMLIdiomHTML has no variables, but the id attribute names an element for CSS, scripts and fragment links, and custom element names must contain a hyphen.
CSSNativeCSS identifiers name classes, IDs, properties, animations and custom properties such as --main-color, and a backslash escape allows any character in them.
Regular expressionsNativeNamed capture groups such as (?<year>[0-9]{4}) give a group a name, and the name follows the identifier rule of the regex engine.
Language Verdict Mechanism
Python native Unicode names with NFKC; hard and soft keywords; __x mangling
JavaScript native Unicode names, $ and _; escapes; #x private names
TypeScript native as JavaScript
Java native Java letters and digits, $; contextual keywords; _ is a keyword
Kotlin native Unicode names; soft and modifier keywords; names in backticks
C# native Unicode names; @ verbatim identifiers; contextual keywords; nameof
Go native letters and digits; upper-case first letter exports; blank _
Rust native XID names with NFC; r# raw identifiers
C native separate name spaces; reserved _X and __x; C23 XID names
C++ native identifiers with special meaning; namespaces; overloading
Bash native variable names of letters, digits and _; function names are looser
PowerShell native $name variables; ${any text} names; case-insensitive
SQL native regular and quoted identifiers; case folding
Regex native named groups (?<name>...)
HTML idiom id and name attributes; custom element names
CSS native identifiers for classes, IDs, properties and custom properties

All the languages in the table have names, so most verdicts are native. HTML has no variables, but the id attribute names an element so that CSS, scripts and links can refer to it, so the verdict is idiom. The languages differ in which characters a name can hold, whether the case matters, whether names are normalized, and how a program can use a keyword as a name.

The example files show these rules. Python shows name mangling, a key that is not a valid name, and the soft keyword match. JavaScript shows a Unicode escape, reserved words as property names, two encodings of café that are two names, and a private field. Java shows contextual keywords and _. C# shows @class and nameof. Go shows export by case and the blank identifier. Rust shows a raw identifier and NFC normalization. C shows separate name spaces and __func__. C++ shows names with special meaning, namespaces and overloading.

PythonGitHub
import keyword


class Account:
    __balance = 0  # a name that starts with two underscores is mangled
    _owner = "ann"  # one underscore is only a convention for "internal"


print([n for n in vars(Account) if "balance" in n or "owner" in n])

# A namespace is a dict of strings, so code can store a key that is not a valid name.
obj = type("Obj", (), {})()
setattr(obj, "my-var", 1)
print(getattr(obj, "my-var"), "my-var".isidentifier())

# The keyword module lists the hard keywords and the soft keywords of this version.
print(len(keyword.kwlist), keyword.softkwlist)

# The soft keyword match is still a valid name outside a match statement.
match = [1, 2]
match match:
    case [a, b]:
        print("matched", a + b)
Output
['_Account__balance', '_owner']
1 False
35 ['_', 'case', 'match', 'type']
matched 3
  • Verdict: native. A name with two leading underscores in a class body is mangled to _Account__balance, and one underscore is only a convention. A namespace is a dictionary of strings, so setattr can store a key such as my-var that is not a valid name. The keyword module lists the hard keywords and the soft keywords, and the soft keyword match still works as a variable name.
#include <iostream>

namespace geo {
double area(double r) { return 3.0 * r * r; }
}

// One name can name several functions; the types of the arguments choose one.
int twice(int x) { return 2 * x; }
double twice(double x) { return 2.0 * x; }

struct Base {
    virtual ~Base() = default;
    virtual int f() const { return 1; }
};
struct Derived final : Base {
    int f() const override { return 2; }
};

int main() {
    // final and override are names with a special meaning only in a class head
    // or after a member declarator, so they can still name variables.
    int final = 3, override = 4;
    std::cout << final + override << "\n";

    // and, or and not are alternative spellings of operators, not names.
    std::cout << std::boolalpha << (true and not false) << "\n";

    // A namespace adds a qualifier, so geo::area and a global area do not clash.
    std::cout << geo::area(1.0) << "\n";
    std::cout << twice(2) << " " << twice(2.5) << "\n";

    Derived d;
    const Base& b = d;
    std::cout << b.f() << " " << __func__ << "\n";
}
Output
7
true
3
4 5
2 main
  • Verdict: native. final and override have a special meaning only in some places, so they can name variables. and, or and not are alternative spellings of operators, not names. A namespace qualifies a name, and overloading lets one name refer to several functions that the types of the arguments choose between.
JavaGitHub
import java.util.List;

public class Main {
    public static void main(String[] args) {
        // Java names can use letters of any script, digits after the first character, _ and $.
        int größe = 3, $count = 4, π2 = 5;
        System.out.println(größe + $count + π2);

        // var and record are contextual keywords, so they can still name a variable.
        int var = 1;
        String record = "r";
        System.out.println(var + record);

        // A Unicode escape is translated before the lexer finds names, so these are one variable.
        int abc = 7;
        System.out.println(\u0061bc);

        // _ alone is a keyword, and it declares a variable that the code does not use.
        for (var _ : List.of(1, 2, 3)) {
            System.out.print("*");
        }
        System.out.println();

        // Character checks only the form of a name, so it accepts the keywords _ and class.
        for (String s : List.of("x1", "1x", "a-b", "_", "class")) {
            boolean ok = Character.isJavaIdentifierStart(s.charAt(0))
                    && s.chars().skip(1).allMatch(Character::isJavaIdentifierPart);
            System.out.println(s + " " + ok);
        }
    }
}
Output
12
1r
7
***
x1 true
1x false
a-b false
_ true
class true
  • Verdict: native. Java names can use letters of any script, $ and _. var and record are contextual keywords, so they can name variables. The compiler translates a Unicode escape before it finds names, so the escape for a and the letter are one variable. _ alone is a keyword and declares an unused variable. Character.isJavaIdentifierStart and isJavaIdentifierPart check only the form, so they accept _ and class.
#include <stdio.h>

#define NAME_OF(x) #x

/* C has separate name spaces: a struct tag, a label and an ordinary name do not clash. */
struct point { int x, y; };

int main(void) {
    struct point point = {1, 2};
    int n = 3, N = 4; /* names are case-sensitive */
    printf("%d %d %d\n", point.x + point.y, n, N);

    /* C23 allows names with letters of other scripts. */
    int größe = 5;
    printf("%d\n", größe);

    /* __func__ is a predefined name that holds the name of the function. */
    printf("%s\n", __func__);

    /* The preprocessor can turn a name into a string. */
    printf("%s\n", NAME_OF(point));

    /* Names that start with __, or with _ and an upper-case letter, are reserved for
       the implementation. A program that declares one has undefined behavior. */
    goto point;
point:
    printf("label point\n");
    return 0;
}
Output
3 3 4
5
main
point
label point
  • Verdict: native. C keeps struct tags, labels and ordinary names in separate name spaces, so point names a tag, a variable and a label at once. Names are case-sensitive. C23 accepts names with letters of other scripts. __func__ holds the name of the function, and the # operator of the preprocessor turns a name into a string. Names that start with __, or with _ and an upper-case letter, are reserved.
using System.Reflection;

// @ makes a keyword usable as a name. The @ is not part of the name.
int @class = 1;
var @event = new { @class };
Console.WriteLine($"{@class} {@event}");

// Contextual keywords such as var, async and record are names outside their context.
int var = 2, async = 3;
Console.WriteLine(var + async);

// A Unicode escape in a name is the same name.
int abc = 4;
Console.WriteLine(\u0061bc);

// nameof gives the name of a variable, type or member as a string, checked by the compiler.
Console.WriteLine(nameof(abc) + " " + nameof(Point.X));

// After compilation, the names of members are metadata that reflection reads.
var fields = typeof(Point).GetFields(BindingFlags.Public | BindingFlags.Instance);
Console.WriteLine(string.Join(" ", fields.Select(f => f.Name)));

class Point
{
    public int X = 1, @Y = 2;
}
Output
1 { class = 1 }
5
4
abc X
X Y
  • Verdict: native. The prefix @ makes a keyword usable as a name, and the @ is not part of the name, so the anonymous type has a property class. Contextual keywords such as var and async are names outside their context. nameof gives a name as a string that the compiler checks, and reflection reads the names of members from metadata.
JavaScriptGitHub
// $ and _ can start a name, and a Unicode escape can spell a name.
const $ = 1, _x = 2;
const \u0061bc = 3;
console.log($ + _x, abc);

// A reserved word is not a valid variable name, but it is a valid property name.
const obj = { class: "c", if: "i" };
console.log(obj.class, obj.if);
for (const src of ["let class = 1", "var let = 1"]) {
  try {
    new Function(src);
    console.log(JSON.stringify(src), "ok");
  } catch (e) {
    console.log(JSON.stringify(src), e.name);
  }
}

// JavaScript does not normalize names: two spellings of "é" give two names.
const nfc = "caf\u00e9", nfd = "cafe\u0301";
const f = new Function(`const ${nfc} = 1, ${nfd} = 2; return [${nfc}, ${nfd}];`);
console.log(f(), nfc === nfd, nfc === nfd.normalize("NFC"));

// A name that starts with # is a private field of a class.
class Counter {
  #n = 0;
  inc() { return ++this.#n; }
}
const c = new Counter();
c.inc();
console.log(c.inc(), Object.keys(c).length);
Output
3 3
c i
"let class = 1" SyntaxError
"var let = 1" ok
[ 1, 2 ] false true
2 0
  • Verdict: native. $ and _ can start a name, and the Unicode escape for a spells the same name as the letter. A reserved word such as class is a valid property name but not a variable name, while let is a valid name in non-strict code. JavaScript does not normalize names, so the two spellings of café are two variables. A name that starts with # is a private field and is not an own key of the object.
package main

import (
	"fmt"
	"go/token"
)

// Total is exported, because its name starts with an upper-case letter.
// total would be visible only inside this package.
func Total(xs ...int) int {
	t := 0
	for _, x := range xs { // _ is the blank identifier: the index is not used
		t += x
	}
	return t
}

func main() {
	π := 3.14159
	größe := 2.0
	fmt.Println(Total(1, 2, 3), π*größe)

	for _, s := range []string{"x1", "1x", "Total", "total", "_", "func", "größe", "a-b"} {
		fmt.Printf("%-6s identifier=%-5v keyword=%-5v exported=%v\n",
			s, token.IsIdentifier(s), token.IsKeyword(s), token.IsExported(s))
	}

	// A name is a letter followed by letters and digits. U+0301, the combining acute accent, is a mark,
	// so the decomposed spelling of café is not an identifier, and Go does not normalize it.
	nfc, nfd := "caf\u00e9", "cafe\u0301"
	fmt.Println(token.IsIdentifier(nfc), token.IsIdentifier(nfd), nfc == nfd)
}
Output
6 6.28318
x1     identifier=true  keyword=false exported=false
1x     identifier=false keyword=false exported=false
Total  identifier=true  keyword=false exported=true
total  identifier=true  keyword=false exported=false
_      identifier=true  keyword=false exported=false
func   identifier=false keyword=true  exported=false
größe  identifier=true  keyword=false exported=false
a-b    identifier=false keyword=false exported=false
true false false
  • Verdict: native. A Go name is a letter followed by letters and digits, and _ counts as a letter. A name that starts with an upper-case letter is exported from its package, so the case of the first letter sets the visibility. _ is the blank identifier and binds nothing. go/token checks the form of a name, the keywords and export. The decomposed spelling of café contains a combining mark, so it is not an identifier.
RustGitHub
// A raw identifier r#name lets a keyword be a name, for example to call code
// from an older edition in which the word was not a keyword.
fn r#match(r#type: &str) -> usize {
    r#type.len()
}

fn main() {
    println!("{}", r#match("abc"));

    // Rust names can use letters of other scripts. rustc warns when all the names
    // of a script could be confused with letters of another script, as with π here.
    let größe = 2;
    let π = 3.0_f64;
    println!("{}", π * größe as f64);

    // The compiler normalizes names to NFC. The second name below is spelled
    // with e and the combining accent U+0301, and it is the same variable.
    let café = 10;
    println!("{}", café + 1);

    // _ is a pattern that binds nothing; a name that starts with _ turns off the unused warning.
    let _unused = 5;
    let _ = r#match("");
}
Output
3
6
11
  • Verdict: native. A raw identifier such as r#match uses a keyword as a name. Rust names can use letters of other scripts, and rustc warns when the names of a script could be confused with letters of another script, as for π. The compiler normalizes names to NFC, so the second spelling of café names the same variable. A name that starts with _ turns off the warning for an unused variable.
  • Case. Most languages are case-sensitive. SQL folds the case of a name that has no quotes, and PowerShell, Fortran, Pascal and Visual Basic ignore case.
  • Sigils. Perl, PHP, Bash and PowerShell put $ before a variable name. In Perl, the sigil also gives the kind of value, such as @ for an array.
  • Quoted names. SQL "order", Kotlin and Scala names in backticks, C# @ and Rust r# let a program use a name that is a keyword or that holds other characters.
  • Naming conventions. snake_case, camelCase, PascalCase and SCREAMING_CASE are conventions, not rules, but Go export and Rust lints depend on case.
  • Scope and binding. The identifier is the text. What it refers to depends on the scope and the bindings at that point in the program. See lexical scope.
  • Names at run time. Reflection reads the names of fields and methods, and a stack trace shows the names of functions. See runtime reflection. C and C++ give __func__, and C# gives nameof.

Pitfalls

  • Confusable characters. Unicode names allow letters that look the same, such as Latin a and Cyrillic а. Two names can look equal and be different. Rust warns about mixed-script confusables, and code review tools can flag non-ASCII names.
  • Names that shadow built-ins. list = [1, 2] in Python or let name in a browser script hides a built-in name in that scope. Later code that uses the built-in fails.
  • New keywords. A new version of a language can make a word a keyword, and old code that uses it as a name stops compiling. Languages use contextual keywords, editions and raw identifiers to reduce this problem.
  • Reserved names in C and C++. Names such as _Data or __count are reserved, and a library header can define a macro with the same name. Do not start names with _ and an upper-case letter or with two underscores.
  • Normalization differences. A name copied from a document can be in another normal form. Python and Rust treat the two forms as one name, and JavaScript treats them as two.
  • Case and the file system. Two names that differ only in case, such as Config and config, are different in the language, but can clash as file names on a file system that ignores case.

Cost

In a compiled language, names have no cost at run time: the compiler turns each use into an address, an offset or a register. Names stay in the output only as metadata for reflection, as debug information or as symbols for the linker. Old C linkers had limits on the length of external names, so the C standard required only 6 significant initial characters in an external identifier before C99, and 31 after9. In a dynamic language such as Python, many names are keys in a dictionary at run time, so a lookup of a global name costs a hash lookup, and a local name in a function is an index into an array.

History

The 1956 FORTRAN manual for the IBM 704 allowed a variable name of "1 to 6 alphabetic or numeric characters", and the first letter gave the type: a name that starts with I, J, K, L, M or N is a fixed-point (integer) variable10. This rule for names that start with I to N stayed in Fortran as implicit typing. C kept short external names for a long time because of the limits of linkers9.

The character set of names grew with Unicode. Unicode Standard Annex 31 gives the default rules that many languages now use8. PEP 3131 of 2007 proposed "to support non-ASCII letters (such as accented characters, Cyrillic, Greek, Kanji, etc.) in Python identifiers", and Python 3.0 added them11. C23 changed the C rule to the Unicode classes XID_Start and XID_Continue9. Wikipedia describes the identifier as "a lexical token" that "names the language's entities"12.

References

  1. The Go Programming Language Specification, Identifiers; Exported identifiers; Blank identifier
  2. The Java Language Specification, Java SE 25 Edition, Chapter 3, 3.8 Identifiers; 3.9 Keywords
  3. Lexical grammar, MDN Web Docs, Identifiers; Keywords
  4. Identifiers, C++ reference, cppreference.com, In declarations
  5. Lexical analysis, The Python Language Reference, 2.3 Names (identifiers and keywords)
  6. Lexical structure, C# language specification, Identifiers
  7. Identifiers, The Rust Reference, Normalization; Raw identifiers
  8. Unicode Standard Annex 31, Unicode Identifiers and Syntax, 2 Default Identifiers
  9. Identifier, C reference, cppreference.com, Reserved identifiers; Translation limits
  10. The FORTRAN Automatic Coding System for the IBM 704 EDPM, Programmer's Reference Manual, IBM, 1956, Chapter 2, Variables
  11. PEP 3131, Supporting Non-ASCII Identifiers, Abstract
  12. Identifier (computer 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.

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