Constant (programming)
Encyclopedia
In computer programming
Computer programming
Computer programming is the process of designing, writing, testing, debugging, and maintaining the source code of computer programs. This source code is written in one or more programming languages. The purpose of programming is to create a program that performs specific operations or exhibits a...

, a constant is an identifier whose associated value cannot typically be altered by the program during its execution (though in some cases this can be circumvented, e.g. using self-modifying code
Self-modifying code
In computer science, self-modifying code is code that alters its own instructions while it is executing - usually to reduce the instruction path length and improve performance or simply to reduce otherwise repetitively similar code, thus simplifying maintenance...

). Many programming languages make an explicit syntactic distinction between constant and variable symbols.

Although a constant's value is specified only once, a constant may be referenced many times in a program. Using a constant instead of specifying a value multiple times in the program can not only simplify code maintenance, but it can also supply a meaningful name for it and consolidate such constant bindings to a standard code location (for example, at the beginning).

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 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. 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 constant variable. A global or static variable can be declared (or a symbol defined in assembly) with a keyword qualifier such as , constant, 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, though some have an option to produce a section specifically dedicated to constants, if so desired. Memory protection can be applied to this area to prevent overwriting of constant variables by errant pointers.

These "constant variables" 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:

  1. 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) {
const float XYZ = someGlobalVariable*someOtherFunction(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:
  1. It is clear to the reader that the object will not be modified further, once set
  2. 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
  3. 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
ALGOL 68 isan imperative computerprogramming language that was conceived as a successor to theALGOL 60 programming language, designed with the goal of a...

. 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
Functional programming
In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state...

 since they favour programming styles with no side-effect (e.g., recursion) or make most declarations immutable
ML programming language
ML is a general-purpose functional programming language developed by Robin Milner and others in the early 1970s at the University of Edinburgh, whose syntax is inspired by ISWIM...

 by default. Some functional languages even forbid side-effects
Purely functional
Purely functional is a term in computing used to describe algorithms, data structures or programming languages that exclude destructive modifications...

 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
Const-correctness
In computer science, const-correctness is the form of program correctness that deals with the proper declaration of objects as mutable or immutable. The term is mostly used in a C or C++ context, and takes its name from the const keyword in those languages....

.

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 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/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 are defined


public interface IReadable
{
IValueInterface aValue { get; }
}

public interface IWritable : IReadable
{
IValueInterface aValue { set; }
}

public class AnObject : IWritable
{
private ConcreteValue _aValue;

public IValueInterface aValue
{
get { return _aValue; }
set { _aValue = value as ConcreteValue; }
}
}


Then, the defined methods select the right interface with read-only or read/write capabilities:


public void DoSomething(IReadable aVariable)
{
// Cannot modify aVariable!
}

public void DoSomethingElse(IWritable aVariable)
{
// Can modify aVariable, so be careful!
}

Object-oriented constants

A constant data structure or object is referred to as "immutable
Immutable object
In object-oriented and functional programming, an immutable object is an object whose state cannot be modified after it is created. This is in contrast to a mutable object, which can be modified after it is created...

" 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.

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 .

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.

Naming conventions

Naming conventions
Naming conventions (programming)
In computer programming, a naming convention is a set of rules for choosing the character sequence to be used for identifiers which denote variables, types and functions etc...

 for constant variables 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 SOME_CONSTANT. In Hungarian notation
Hungarian notation
Hungarian notation is an identifier naming convention in computer programming, in which the name of a variable or function indicates its type or intended use...

, a "k" prefix
Prefix
A prefix is an affix which is placed before the root of a word. Particularly in the study of languages,a prefix is also called a preformative, because it alters the form of the words to which it is affixed.Examples of prefixes:...

 signifies constants as well as macros and enumerated type
Enumerated type
In computer programming, an enumerated type is a data type consisting of a set of named values called elements, members or enumerators of the type. The enumerator names are usually identifiers that behave as constants in the language...

s.

See also

  • Address constant
    Address constant
    In IBM/360 , an address constant or "adcon" is an Assembly language data type whose value refers directly to another value stored elsewhere in the computer memory using its address. An address constant can be one, two, three or four bytes long...

    s for the IBM/360 and Z/Architecture
    Z/Architecture
    z/Architecture, initially and briefly called ESA Modal Extensions , refers to IBM's 64-bit computing architecture for IBM mainframe computers. IBM introduced its first z/Architecture-based system, the zSeries Model 900, in late 2000. Later z/Architecture systems include the IBM z800, z990, z890,...

    platform
The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK