ArticleslgStudy

computer science

Constant (computer programming)

Constant (computer programming) is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Constant (computer programming) rather than just read about it. In short: In computer programming, a constant is a value that is not altered by the program during normal execution. When associated with an identifier, a constant is said to be "named," although the terms "constant" and "named constant" are often used interchangeably.

Key takeaways

  • Constant (computer programming) belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Constant (computer programming) to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Constant (computer programming) from memory before moving on to harder problems.

Reference excerpt

In computer programming, a constant is a value that is not altered by the program during normal execution. When associated with an identifier, 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. To simplify, constants' values remains, while the values of variables varies, hence both their names. Constants are useful for both programmers and compilers: for programmers, they are a form of self-documenting code and allow reasoning about correctness, while for compilers, they allow compile-time and run-time checks that verify that constancy assumptions are not violated, and allow or simplify some compiler optimizations. 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 objects, and constant types (const). Typical examples of compile-time constants include mathematical constants, values from standards (here maximum transmission unit), or internal configuration values (here characters per line), such as these C examples:

Typical examples of run-time constants are values calculated based on inputs to a function, such as this C++ example:

Use Some programming languages make an explicit syntactic distinction between constant and variable symbols, for example considering assignment 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) and can be self documenting by supplying a meaningful name for a value, for instance, PI 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 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 named by a macro. A third way is by declaring and defining a variable as being "constant". A global variable or static variable can be declared (or a symbol defined in assembly) with a keyword qualifier such as const, constexpr, constant, or final (when it is applied to primitive types), 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 const/constexpr provides the latter:

while in Ada, there are universal numeric types that can be used, if desired:

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

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:

… excerpt ends here. Continue reading the full article.

Worked examples

Example 1 — a first encounter with Constant (computer programming)

Start with the simplest possible case. Write down what Constant (computer programming) claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Constant (computer programming) before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Constant (computer programming) ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Constant (computer programming)

In research
Constant (computer programming) appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Constant (computer programming) in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Constant (computer programming) is common in secondary-school and first-year university syllabi. It links to neighbouring topics Constants, Programming constructs, so understanding it makes those chapters shorter.
In everyday life
Look for Constant (computer programming) outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Constant (computer programming)” →

How to study Constant (computer programming) in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Constant (computer programming) means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Constant (computer programming) out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Constant (computer programming) in simple terms?

In computer programming, a constant is a value that is not altered by the program during normal execution. When associated with an identifier, a constant is said to be "named," although the terms "constant" and "named constant" are often used interchangeably.

Why does Constant (computer programming) matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Constant (computer programming)?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Constant (computer programming).

Tags

  • Constants
  • Programming constructs

Keep exploring