Constant (computer science)
   HOME

TheInfoList



OR:

In
computer programming Computer programming is the process of performing a particular computation (or more generally, accomplishing a specific computing result), usually by designing and building an executable computer program. Programming involves tasks such as anal ...
, a constant is a
value Value or values may refer to: Ethics and social * Value (ethics) wherein said concept may be construed as treating actions themselves as abstract objects, associating value to them ** Values (Western philosophy) expands the notion of value beyo ...
that should not be altered by the
program Program, programme, programmer, or programming may refer to: Business and management * Program management, the process of managing several related projects * Time management * Program, a part of planning Arts and entertainment Audio * Programm ...
during normal
execution Capital punishment, also known as the death penalty, is the state-sanctioned practice of deliberately killing a person as a punishment for an actual or supposed crime, usually following an authorized, rule-governed process to conclude that ...
, i.e., the value is ''constant''. When associated with an
identifier An identifier is a name that identifies (that is, labels the identity of) either a unique object or a unique ''class'' of objects, where the "object" or class may be an idea, physical countable object (or class thereof), or physical noncountable ...
, a constant is said to be "named," although the terms "constant" and "named constant" are often used interchangeably. This is contrasted with a '' variable,'' which is an identifier with a value that can be changed during normal execution, i.e., the value is ''variable.'' Constants are useful for both programmers and
compiler In computing, a compiler is a computer program that translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primarily used for programs tha ...
s: For programmers they are a form of
self-documenting In computer programming, self-documenting (or self-describing) source code and user interfaces follow naming conventions and structured programming conventions that enable use of the system without prior specific knowledge. In web development, se ...
code and allow reasoning about correctness, while for compilers they allow
compile-time In computer science, compile time (or compile-time) describes the time window during which a computer program is compiled. The term is used as an adjective to describe concepts related to the context of program compilation, as opposed to concept ...
and run-time checks that verify that constancy assumptions are not violated, and allow or simplify some
compiler optimization In computing, an optimizing compiler is a compiler that tries to minimize or maximize some attributes of an executable computer program. Common requirements are to minimize a program's execution time, memory footprint, storage size, and power con ...
s. There are various specific realizations of the general notion of a constant, with subtle distinctions that are often overlooked. The most significant are: compile-time (statically valued) constants, run-time (dynamically valued) constants,
immutable object In object-oriented and functional programming, an immutable object (unchangeable object) is an object whose state cannot be modified after it is created.Goetz et al. ''Java Concurrency in Practice''. Addison Wesley Professional, 2006, Section 3. ...
s, and constant types ( const). Typical examples of compile-time constants include mathematical constants, values from standards (here
maximum transmission unit In computer networking, the maximum transmission unit (MTU) is the size of the largest protocol data unit (PDU) that can be communicated in a single network layer transaction. The MTU relates to, but is not identical to the maximum frame size tha ...
), or internal configuration values (here
characters per line In typography and computing, characters per line (CPL) or terminal width refers to the maximal number of monospaced characters that may appear on a single line. It is similar to line length in typesetting. History The limit of the line length ...
), such as these C examples: const float PI = 3.1415927; // maximal single float precision const unsigned int MTU = 1500; // Ethernet v2, RFC 894 const unsigned int COLUMNS = 80; Typical examples of run-time constants are values calculated based on inputs to a function, such as this
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
example: void f(std::string s)


Use

Some
programming language A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language. The description of a programming ...
s make an explicit syntactic distinction between constant and variable symbols, for example considering
assignment Assignment, assign or The Assignment may refer to: * Homework * Sex assignment * The process of sending National Basketball Association players to its development league; see Computing * Assignment (computer science), a type of modification to ...
to a constant to be a syntax error, while in other languages they are considered syntactically the same (both simply an identifier), and the difference in treatment is semantic (assignment to an identifier is syntactically valid, but if the identifier is a constant it is semantically invalid). A constant value is defined once and can be referenced many times throughout a program. Using a constant instead of specifying the same value multiple times can simplify code maintenance (as in
don't repeat yourself "Don't repeat yourself" (DRY) is a principle of software development aimed at reducing repetition of software patterns, replacing it with abstractions or using data normalization to avoid redundancy. The DRY principle is stated as "Every piece of ...
) and can be self documenting by supplying a meaningful name for a value, for instance, instead of 3.1415926.


Comparison with literals and macros

There are several main ways to express a data value that doesn't change during program execution that are consistent across a wide variety of programming languages. One very basic way is by simply writing a
literal Literal may refer to: * Interpretation of legal concepts: ** Strict constructionism ** The plain meaning rule The plain meaning rule, also known as the literal rule, is one of three rules of statutory construction traditionally applied by ...
number, character, or string into the program code, which is straightforward in C, C++, and similar languages. In assembly language, literal numbers and characters are done using the "immediate mode" instructions available on most microprocessors. The name "immediate" comes from the values being available immediately from the instruction stream, as opposed to loading them indirectly by looking up a memory address.Ex
IBM Systems Information
Instruction Set - Assembler Language Reference for PowerPC.
On the other hand, values longer than the microprocessor's word length, such as strings and arrays, are handled indirectly and assemblers generally provide a "data" pseudo-op to embed such data tables in a program. Another way is by defining a symbolic macro. Many high-level programming languages, and many assemblers, offer a macro facility where the programmer can define, generally at the beginning of a source file or in a separate definition file, names for different values. A preprocessor then replaces these names with the appropriate values before compiling, resulting in something functionally identical to using literals, with the speed advantages of immediate mode. Because it can be difficult to maintain code where all values are written literally, if a value is used in any repetitive or non-obvious way, it is often done as a macro. A third way is by declaring and defining a variable as being "constant". A
global variable In computer programming, a global variable is a variable with global scope, meaning that it is visible (hence accessible) throughout the program, unless shadowed. The set of all global variables is known as the ''global environment'' or ''global s ...
or
static variable In computer programming, a static variable is a variable that has been allocated "statically", meaning that its lifetime (or "extent") is the entire run of the program. This is in contrast to shorter-lived automatic variables, whose storage is ...
can be declared (or a symbol defined in assembly) with a keyword qualifier such as , , or , meaning that its value will be set at compile time and should not be changeable at runtime. Compilers generally put static constants in the text section of an object file along with the code itself, as opposed to the data section where non-const initialized data is kept. Some compilers can produce a section specifically dedicated to constants. Memory protection can be applied to this area to prevent overwriting of such constants by errant pointers. These constants differ from literals in a number of ways. Compilers generally place a constant in a single memory location identified by symbol, rather than spread throughout the executable as with a macro. While this precludes the speed advantages of immediate mode, there are advantages in memory efficiency, and debuggers can work with these constants at runtime. Also while macros may be redefined accidentally by conflicting header files in C and C++, conflicting constants are detected at compile time. Depending upon the language, constants can be untyped or typed. In C and C++, macros provide the former, while provides the latter: #define PI 3.1415926535 const float pi2 = 3.1415926535; while in Ada, there are universal numeric types that can be used, if desired: pi : constant := 3.1415926535; pi2 : constant float := 3.1415926535; with the untyped variant being implicitly converted to the appropriate type upon each use.


Dynamically-valued constants

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 on the stack or in registers, to dynamically allocated memory that is accessed by pointer, and to parameter lists in function headers. Dynamically valued constants do not designate a variable as residing in a specific region of memory, nor are the values set at compile time. In C++ code such as float func(const float ANYTHING) the expression that the constant is initialized to are not themselves constant. Use of constantness is not necessary here for program legality or semantic correctness, but has three advantages: # It is clear to the reader that the object will not be modified further, once set # Attempts to change the value of the object (by later programmers who do not fully understand the program logic) will be rejected by the compiler # The compiler may be able to perform code optimizations knowing that the value of the object will not change once created. Dynamically valued constants originated as a language feature with
ALGOL 68 ALGOL 68 (short for ''Algorithmic Language 1968'') is an imperative programming language that was conceived as a successor to the ALGOL 60 programming language, designed with the goal of a much wider scope of application and more rigorously d ...
. Studies of Ada and C++ code have shown that dynamically valued constants are used infrequently, typically for 1% or less of objects, when they could be used much more, as some 40–50% of local, non-class objects are actually invariant once created. On the other hand, such "immutable variables" tend to be the default in functional languages since they favour programming styles with no side-effect (e.g., recursion) or make most declarations immutable by default, such as ML. Purely functional languages even forbid side-effects entirely. Constantness is often used in function declarations, as a promise that when an object is passed by reference, the called function will not change it. Depending on the syntax, either a pointer or the object being pointed to may be constant, however normally the latter is desired. Especially in C++ and C, the discipline of ensuring that the proper data structures are constant throughout the program is called
const-correctness In some programming languages, const is a type qualifier (a keyword applied to a data type) that indicates that the data is read-only. While this can be used to declare constants, in the C family of languages differs from similar constructs i ...
.


Constant function parameters

In C/C++, it is possible to declare the parameter of a function or method as constant. This is a guarantee that this parameter cannot be modified after the first assignment (inadvertently). If the parameter is a pre-defined (built-in) type, it is
called by value In a programming language, an evaluation strategy is a set of rules for evaluating expressions. The term is often used to refer to the more specific notion of a ''parameter-passing strategy'' that defines the kind of value that is passed to the f ...
and cannot be modified. If it is a user-defined type, the variable is the pointer address, which cannot be modified either. However, the content of the object can be modified without limits. Declaring parameters as constants may be a way to signalise that this value ''should'' not be changed, but the programmer must keep in mind that checks about modification of an object cannot be done by the compiler. Besides this feature, it is in C++ also possible to declare a function or method as . This prevents such functions or methods from modifying anything but local variables. In C#, the keyword exists, but does not have the same effect for function parameters, as it is the case in C/C++. There is, however, a way to "stir" the compiler to do make the check, albeit it is a bit tricky. To get the same effect, first, two
interfaces Interface or interfacing may refer to: Academic journals * ''Interface'' (journal), by the Electrochemical Society * '' Interface, Journal of Applied Linguistics'', now merged with ''ITL International Journal of Applied Linguistics'' * '' Int ...
are defined public interface IReadable public interface IWritable : IReadable public class AnObject : IWritable Then, the defined methods select the right interface with read-only or read/write capabilities: public void DoSomething(IReadable aVariable) public void DoSomethingElse(IWritable aVariable)


Object-oriented constants

A constant data structure or object is referred to as " immutable" in object-oriented parlance. An object being immutable confers some advantages in program design. For instance, it may be "copied" simply by copying its pointer or reference, avoiding a time-consuming copy operation and conserving memory. Object-oriented languages such as C++ extend constantness even further. Individual members of a struct or class may be made const even if the class is not. Conversely, the keyword allows a class member to be changed even if an object was instantiated as . Even functions can be const in C++. The meaning here is that only a const function may be called for an object instantiated as const; a const function doesn't change any non-mutable data. C# has both a and a qualifier; its const is only for compile-time constants, while readonly can be used in constructors and other runtime applications.


Java

Java has a qualifier called that prevents changing a reference and makes sure it will never point to a different object. This does not prevent changes to the referred object itself. Java's is basically equivalent to a ''pointer'' in C++. It does not provide the other features of . In
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
, the qualifier states that the affected data member or variable is not assignable, as below: final int i = 3; i = 4; // Error! Cannot modify a "final" object It must be decidable by the compilers where the variable with the marker is initialized, and it must be performed only once, or the class will not compile. Java's and C++'s keywords have the same meaning when applied with primitive variables. const int i = 3; // C++ declaration i = 4; // Error! Considering pointers, a reference in Java means something similar to pointer in C++. In C++, one can declare a "constant pointer type". Foo *const bar = mem_location; // const pointer type Here, must be initialised at the time of declaration and cannot be changed again, but what it points ''is'' modifiable. I.e. is valid. It just can't point to another location. Final references in Java work the same way except that they can be declared uninitialized. final Foo i; // a Java declaration Note: Java does not support pointers. It is because pointers (with restrictions) are the default way of accessing objects in Java, and Java does not use stars to indicate them. For example, in the last example is a pointer and can be used to access the instance. One can also declare a pointer to "read-only" data in C++. const Foo *bar; Here can be modified to point anything, anytime; just that pointed value cannot be modified ''through'' pointer. There is no equivalent mechanism in Java. Thus there are also no methods. Const-correctness cannot be enforced in Java, although by use of interfaces and defining a read-only interface to the class and passing this around, one can ensure that objects can be passed around the system in a way that they cannot be modified.
Java collections framework The Java collections framework is a set of classes and interfaces that implement commonly reusable collection data structures. Although referred to as a framework, it works in a manner of a library. The collections framework provides both interf ...
provides a way to create an immutable wrapper of a via and similar methods. A method in Java can be declared "final", meaning that it cannot be overridden in subclasses.


C#

In C#, the qualifier has the same effect on data members that does in Java and the does in C++; the modifier has an effect similar (yet typed and class-scoped) to that of in C++. The other, inheritance-inhibiting effect of Java's when applied to methods and classes is induced in C# with the aid of the keyword . Unlike C++, C# does not permit methods and parameters to be marked as . However one may also pass around read-only subclasses, and the
.NET Framework The .NET Framework (pronounced as "''dot net"'') is a proprietary software framework developed by Microsoft that runs primarily on Microsoft Windows. It was the predominant implementation of the Common Language Infrastructure (CLI) until bein ...
provides some support for converting mutable collections to immutable ones which may be passed as read-only wrappers.


By paradigm

Treatment of constants varies significantly by
programming paradigm Programming paradigms are a way to classify programming languages based on their features. Languages can be classified into multiple paradigms. Some paradigms are concerned mainly with implications for the execution model of the language, suc ...
. Const-correctness is an issue in imperative languages like C++ because by default
name binding In programming languages, name binding is the association of entities (data and/or code) with identifiers. An identifier bound to an object is said to reference that object. Machine languages have no built-in notion of identifiers, but name-objec ...
s typically create variables, which can vary, as the name suggests, and thus if one wishes to mark a binding as constant this requires some additional indication. In other programming language paradigms related issues arise, with some analogs to const-correctness found. In
functional programming In computer science, functional programming is a programming paradigm where programs are constructed by applying and composing functions. It is a declarative programming paradigm in which function definitions are trees of expressions tha ...
, data are typically constant by default, rather than variable by default. Instead of assigning a value to a variable (a storage space with a name and potentially variable value), one creates a binding of a name to a value, such as by the construct in many dialects of
Lisp A lisp is a speech impairment in which a person misarticulates sibilants (, , , , , , , ). These misarticulations often result in unclear speech. Types * A frontal lisp occurs when the tongue is placed anterior to the target. Interdental lispin ...
. In some functional languages, particularly multiparadigm ones such as
Common Lisp Common Lisp (CL) is a dialect of the Lisp programming language, published in ANSI standard document ''ANSI INCITS 226-1994 (S20018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived fr ...
, modifying data is commonplace, while in others it is avoided or considered exceptional; this is the case for
Scheme A scheme is a systematic plan for the implementation of a certain idea. Scheme or schemer may refer to: Arts and entertainment * ''The Scheme'' (TV series), a BBC Scotland documentary series * The Scheme (band), an English pop band * ''The Schem ...
(another Lisp dialect), which uses the construct to modify data, with the exclamation point drawing attention to this. Such languages achieve the goals of const-correctness by default, drawing attention to modification rather than constantness. In a number of object-oriented languages, there is the concept of an
immutable object In object-oriented and functional programming, an immutable object (unchangeable object) is an object whose state cannot be modified after it is created.Goetz et al. ''Java Concurrency in Practice''. Addison Wesley Professional, 2006, Section 3. ...
, which is particularly used for basic types like strings; notable examples include Java, JavaScript, Python, and C#. These languages vary in whether user-defined types can be marked as immutable, and may allow particular fields (attributes) of an object or type to be marked as immutable. In some multiparadigm languages that allow both object-oriented and functional styles, both of these features may be combined. For example, in
OCaml OCaml ( , formerly Objective Caml) is a general-purpose, multi-paradigm programming language Programming paradigms are a way to classify programming languages based on their features. Languages can be classified into multiple paradigms. ...
object fields are immutable by default and must be explicitly marked with the keyword to be mutable, while in Scala, bindings are explicitly immutable when defined with for "value" and explicitly mutable when defined with for "variable".


Naming conventions

Naming conventions A naming convention is a convention (generally agreed scheme) for naming things. Conventions differ in their intents, which may include to: * Allow useful information to be deduced from the names based on regularities. For instance, in Manhatta ...
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 .Microsoft Office XP Developer: Constant Names
/ref> In
Hungarian notation Hungarian notation is an identifier naming convention in computer programming, in which the name of a variable or function indicates its intention or kind, and in some dialects its type. The original Hungarian notation uses intention or kind in ...
, a "k"
prefix A prefix is an affix which is placed before the stem of a word. Adding it to the beginning of one word changes it into another word. For example, when the prefix ''un-'' is added to the word ''happy'', it creates the word ''unhappy''. Particul ...
signifies constants as well as macros and
enumerated type In computer programming, an enumerated type (also called enumeration, enum, or factor in the R programming language, and a categorical variable in statistics) is a data type consisting of a set of named values called ''elements'', ''members'', '' ...
s. One enforced convention is that in
Ruby A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called ...
, any variable that begins with a capital letter is considered a constant, including class names.


See also

* Address constants for the
IBM/360 The IBM System/360 (S/360) is a family of mainframe computer systems that was announced by IBM on April 7, 1964, and delivered between 1965 and 1978. It was the first family of computers designed to cover both commercial and scientific applic ...
and
Z/Architecture z/Architecture, initially and briefly called ESA Modal Extensions (ESAME), is IBM's 64-bit complex instruction set computer (CISC) instruction set architecture, implemented by its mainframe computers. IBM introduced its first z/Architect ...
platform


Notes


References

{{DEFAULTSORT:Constant (Programming) Programming constructs