Constant (programming)

from Wikipedia, the free encyclopedia

A constant (from Latin constans , 'fixed') in a computer program is a container for a size that cannot be changed after it has been assigned. The opposite of this is a variable .

In the source code, constants usually have semantic identifiers , which simplifies handling and should prevent confusion with other constants. The term is, however, also literals used (literal constant) that have no semantic identifiers. It is therefore clearer to speak of symbolic constants for freely definable constants .

Types of constants

A distinction is made between different types of constants.

  • Literal constants
    "Hello World!"
    
  • Constants that are set at compile time. The compiler replaces each occurrence of the constant with the respective value.
    const string hello = "Hello World!";
    
  • Constants that are set at compile time. However, the value is only read out at runtime.
    readonly string hello = "Hello World!";
    
  • Constants that are specified at runtime.
    let hello = "Hello World!"
    
  • Meta-constants that control the behavior of the preprocessor , but are not part of the program.
    #define DEBUG
    

Runtime constants through encapsulation

In object-oriented programming languages, it is possible to simulate a runtime constant by encapsulating a variable in an object and making only reading methods available:

public MyObject(string name)
{
   public string Name { get; } = name;
}

In functional programming languages, the variable can be encapsulated in a closure :

public Func<string> Create(string name)
{
   return () => name;
}