FACTOID # 83: More than half of Indonesia's primary school teachers are under 30years of age .
 
 Home   Encyclopedia   Statistics   Countries A-Z   Flags   Maps   Education   Forum   FAQ   About 
 
 
 
WHAT'S NEW
RECENT ARTICLES
More Recent Articles »
 

SEARCH ALL

FACTS & STATISTICS    Advanced view

Search encyclopedia, statistics and forums:

 

 

(* = Graphable)

 

 


Encyclopedia > 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. Computer science is the study of the theoretical foundations of information and computation and their implementation and application in computer systems. ... In computer science, an immutable object, as opposed to a mutable object, is a kind of object whose internal states cannot be modified. ... In computer science, an immutable object, as opposed to a mutable object, is a kind of object whose internal states cannot be modified after it is created. ... The C Programming Language, Brian Kernighan and Dennis Ritchie, the original edition that served for many years as an informal specification of the language The C programming language is a general-purpose, procedural, imperative computer programming language developed in the early 1970s by Dennis Ritchie for use on the UNIX... C++ (generally pronounced see plus plus) is a general-purpose programming language. ...


The idea of const-ness does not imply that the variable as it is stored in the computer's memory is unwriteable. Rather, const-ness is a compile-time construct that indicates what a programmer may do, not necessarily what he or she can do. An illustration of a modern personal computer. ... To meet Wikipedias quality standards, this article or section may require cleanup. ... In computer science, compile time, as opposed to runtime, is the time when a compiler compiles code written in a programming language into an executable form. ...


In addition, a class method can be declared as const, indicating that calling that method does not change the object. Such const methods can only call other const methods but cannot assign member variables. (In C++, a member variable can be declared as mutable, indicating that a const method can change its value. Mutable member variables can be used for caching and reference counting, where the logical meaning of the object is unchanged, but the object is not physically constant since its bitwise representation may change.) Used mainly in object-oriented programming, the term method refers to a piece of code that is exclusively associated either with a class (called class methods or static methods) or with an object (called instance methods). ... In computer science, data that has several parts can be divided into fields. ... Look up cache in Wiktionary, the free dictionary. ... In computer science, reference counting is a technique of storing the number of references, pointers, or handles to a resource such as an object or block of memory. ...

Contents


C++ syntax

In C++, all data types, including those defined by the user, can be declared const, and all objects should be unless they need to be modified. Such proactive use of const makes values "easier to understand, track, and reason about,"[1] and thus, it increases the readability and comprehensibility of code and makes working in teams and maintaining code simpler because it communicates something about a value's intended use.


Simple data types

For simple data types, applying the const qualifier is straightforward. It can go on either side of the type for historical reasons (that is, const char foo = 'a'; is equivalent to char const foo = 'a';). On some implementations, using const on both sides of the type (for instance, const char const) generates a warning but not an error.


Pointers and references

For pointer and reference types, the syntax is slightly more subtle. A pointer object can be declared as a const pointer or a pointer to a const object (or both). A const pointer cannot be reassigned to point to a different object from the one it is initially assigned, but it can be used to modify the object that it points to (called the "pointee"). (Reference variables are thus an alternate syntax for const pointers.) A pointer to a const object, on the other hand, can be reassigned to point to another object of the same type or of a convertible type, but it cannot be used to modify any object. A const pointer to a const object can also be declared and can neither be used to modify the pointee nor be reassigned to point to another object. The following code illustrates these subtleties:

 void Foo( int * ptr, int const * ptrToConst, int * const constPtr, int const * const constPtrToConst ) { *ptr = 0; // OK: modifies the pointee ptr = 0; // OK: modifies the pointer *ptrToConst = 0; // Error! Cannot modify the pointee ptrToConst = 0; // OK: modifies the pointer *constPtr = 0; // OK: modifies the pointee constPtr = 0; // Error! Cannot modify the pointer *constPtrToConst = 0; // Error! Cannot modify the pointee constPtrToConst = 0; // Error! Cannot modify the pointer } 

To render the syntax for pointers more comprehensible, a rule of thumb is to read the declaration from right to left. Thus, everything before the star can be identified as the pointee type and everything to after are the pointer properties. (For instance, in our example above, constPtrToConst can be read as a const pointer that refers to a const int.) A rule of thumb is an easily learned and easily applied procedure for approximately calculating or recalling some value, or for making some determination. ...


References follow similar rules. A declaration of a const reference is redundant since references can never be made to refer to another object:

 int i = 42; int const & refToConst = i; // OK int & const constRef = i; // Error the "const" is redundant 

Even more complicated declarations can result when using multidimensional arrays and references (or pointers) to pointers. Generally speaking, these should be avoided or replaced with higher level structures because they are confusing and prone to error.


Methods

In order to take advantage of the design-by-contract strategy for user-defined types (structs and classes), which can have methods as well as member data, the programmer must tag methods as const if they don't modify the object's data members. Applying the const qualifier to methods thus is an essential feature for const-correctness, and is not available in many other object-oriented languages such as Java and C# or in Microsoft's C++/CLI or Managed extensions for C++. While const methods can be called by const and non-const objects alike, non-const methods can only be invoked by non-const objects. This example illustrates: Object-oriented programming (OOP) is a computer programming paradigm in which a software system is modeled as a set of objects that interact with each other. ... Java is an object-oriented programming language developed by James Gosling and colleagues at Sun Microsystems in the early 1990s. ... The title given to this article is incorrect due to technical limitations. ... Microsoft Corporation (NASDAQ: MSFT, SEHK: 4338) is an American multinational computer technology corporation that has global annual sales of over 41. ... C++/CLI (Common Language Infrastructure) is the newer language specification due to supersede Managed Extensions for C++. Completely reviewed to simplify the older Managed C++ syntax, it provides much more clarity over code readability than Managed C++. Like Microsoft . ... It has been suggested that this article or section be merged with Managed Extensions for C++. (Discuss) Managed C++ is one of Microsofts new managed languages for their . ...

 class C { int i; public: int Get() const // Note the "const" tag { return i; } void Set(int j) // Note the lack of "const" { i = j; } }; void Foo(C& nonConstC, const C& constC) { int y = nonConstC.Get(); // Ok int x = constC.Get(); // Ok: Get() is const nonConstC.Set(10); // Ok: nonConstC is modifiable constC.Set(10); // Error! Set() is a non-const method and constC is a const-qualified object } 

Often the programmer will supply both a const and a non-const method with the same name (but possibly quite different uses) in a class to accommodate both types of callers. Consider:

 class MyArray { int data[100]; public: int & Get(int i) { return data[i]; } int const & Get(int i) const { return data[i]; } }; void Foo( MyArray & array, MyArray const & constArray ) { // Get a reference to an array element // and modify its referenced value. array.Get( 5 ) = 42; constArray.Get( 5 ) = 42; // Error! } 

The const-ness of the calling object determines which version of MyArray::Get() will be invoked and thus whether or not the caller is given a reference with which he can manipulate or only observe the private data in the object. (Returning a const reference to an int, instead of merely returning the int by value, may be overkill in the second method, but the same technique can be used for arbitrary types, as in the Standard Template Library.) The Standard Template Library (STL) is a software library. ...


Loopholes to const-correctness

There are two loopholes to pure const-correctness in C and C++. They exist primarily for compatibility with existing code.


The first, which applies only to C++, is the use of const_cast, which allows the programmer to strip the const qualifier, making any object modifiable. The necessity of stripping the qualifier arises when using existing code and libraries that cannot be modified but which are not const-correct. For instance, consider this code:

 // Prototype for a function which we cannot change but which // we know does not modify the pointee passed in. void LibraryFunc(int *ptr, int size); void CallLibraryFunc(int const *ptr, int size) { LibraryFunc(ptr, size); // Error! Drops const qualifier int *nonConstPtr = const_cast<int*>(ptr); // Strip qualifier LibraryFunc(nonConstPtr, size); // OK } 

The other loophole applies both to C and C++. Specifically, the languages dictate that member pointers and references are "shallow" with respect to the const-ness of their owners — that is, a containing object that is const has all const members except that member pointees (and referees) are still mutable. To illustrate, consider this code:

 struct S { int val; int *ptr; }; void Foo(const S & s) { int i = 42; s.val = i; // Error: s is const, so val is a const int s.ptr = &i; // Error: s is const, so ptr is a const pointer to int *s.ptr = i; // OK: the data pointed to by ptr is always mutable, // even though this is sometimes not desirable } 

Although the object s passed to Foo() is constant, which makes all of its members constant, the pointee accessible through s.ptr is still modifiable, though this is not generally desirable from the standpoint of const-correctness because s may solely own the pointee. For this reason, some have argued that the default for member pointers and references should be "deep" const-ness, which could be overridden by a mutable qualifier when the pointee is not owned by the container, but this strategy would create compatibility issues with existing code. Thus, for historical reasons, this loophole remains open in C and C++.


Volatile-correctness

Another qualifier in C and C++, volatile, indicates that an object may be changed by something external to the program at any time and so must be re-read from memory every time it is accessed. The qualifier is most often found in embedded systems, in systems manipulating hardware directly, and in multithreaded applications. It can be used in exactly the same manner as const in declarations of variables, pointers, references, and member functions, and in fact, volatile is sometimes used to implement a similar design-by-contract strategy which might be called volatile-correctness,[2] though this is far less common than const-correctness. The volatile qualifier also can be stripped by const_cast, and it can be combined with the const qualifier as in this sample: To meet Wikipedias quality standards, this article or section may require cleanup. ... Hardware is the general term that is used to describe physical artifacts of a technology. ... Many programming languages, operating systems, and other software development environments support what are called threads of execution. ...

 // Set up a reference to a read-only hardware register that is // mapped in a hard-coded memory location. const volatile int & hardwareRegister = *reinterpret_cast<int*>(0x8000); int currentValue = hardwareRegister; // Read the memory location int newValue = hardwareRegister; // Read it again hardwareRegister = 5; // Error! Cannot write to a const location 

Because hardwareRegister is volatile, there is no guarantee that it will hold the same value on two successive reads even though the programmer cannot modify it. The semantics here indicate that the register's value is read-only but not necessarily unchanging.


We can also create volatile pointers, though their applications are rarer:

 // Set up a pointer to a read-only memory-mapped register that // contains a memory address for us to dereference const int * volatile const tableLookup = reinterpret_cast<int*>(0x8004); int currentTableValue = *tableLookup; // Dereference the memory location int newTableValue = *tableLookup; // Dereference it again tableLookup = &currentTableValue; // Error! Cannot modify a const pointer 

Since the address held in the tableLookup pointer can change implicitly, each deference might take us to a different location in a memory-mapped lookup table. In computer science, a lookup table is a data structure, usually an array or associative array, used to replace a runtime computation with a simpler lookup operation. ...


restrict in C99

The C99 language special cases a restrict qualified pointer to a const qualified type in order to notify a compiler that it can assume "strong const" semantics. For example, a compiler is allowed to transform: The C Programming Language, Brian Kernighan and Dennis Ritchie, the original edition that served for many years as an informal specification of the language The C programming language is a general-purpose, procedural, imperative computer programming language developed in the early 1970s by Dennis Ritchie for use on the UNIX...

 void foo(int *); int bar(int *a) { const int * restrict b = a; foo((int*)b); return *b; } 

into:

 int bar(int *a) { int ret = *a; foo(a); return ret; } 

However, programmers shouldn't use the restrict qualifier unless they understand the formalism given in the standard because it's extremely easy to create undefined code like the seemingly benign:

 int val; int * restrict a = &val; // ok int * restrict b = &val; // ok int * restrict c = a; // undefined int * d = a; // ok int * restrict e = d; // undefined 

final in Java

In Java, the qualifier final states that the affected data member or variable is not assignable, as below: Java is an object-oriented programming language developed by James Gosling and colleagues at Sun Microsystems in the early 1990s. ...

 final int i = 3; i = 4; // Error! Cannot modify a "final" object 

It must be decidable by the compilers where the variable with the final marker is initialized, and it must be performed only once, or the class will not compile. Unlike C++'s const, the Java final keyword only protects a variable from assignment, and does not guarantee its immutability. The keyword final can be given to a method definition in Java, but unlike in C++ its semantics are that the method cannot be overridden in subclasses.


It is interesting to note that whereas Java's final and C++'s const keywords have the same meaning when applied with primitive variables, their meanings diverge when applied to method definitions. Java cannot simulate C++'s const methods. Similarly, C++ does not have any feature equivalent to Java's final modifier for methods, although its effect on classes can be simulated by a clever abuse of the C++ friend keyword.[3]


Interestingly, the Java language specification regards const as a reserved keyword — i.e., one that cannot be used as variable identifier — but assigns no semantics to it. It is thought that the reservation of the keyword occurred to allow for an extension of the Java language to include C++-style const methods. The enhancement request ticket in the Java community process for implementing const correctness in Java was recently closed, implying that const correctness will probably never find its way into the official Java specification.


const and readonly in C#

In C#, the qualifier readonly has the same effect on data members that final does in Java; const has an effect similar (but not equivalent) to that of const in C and C++. (The other, inheritance-inhibiting effect of Java's final when applied to methods and classes is induced in C# with the aid of a third keyword, sealed.) The title given to this article is incorrect due to technical limitations. ...


References

  1. Herb Sutter and Andrei Alexandrescu (2005). C++ Coding Standards. p. 30. Boston: Addison Wesley. ISBN 0321113586
  2. "Generic<Programming>: volatile — Multithreaded Programmer’s Best Friend Volatile-Correctness or How to Have Your Compiler Detect Race Conditions for You" by Andrei Alexandrescu in the C/C++ Users Journal's C++ Experts Forum
  3. C++ Style and Technique FAQ by Bjarne Stroustrup

Herb Sutter is one of the most prominent C++ experts. ... Andrei Alexandrescu is widely regarded as one of the foremost experts on advanced C++ programming. ... C/C++ Users Journal is a printed computer magazine. ... Bjarne Stroustrup Bjarne Stroustrup (born December 30, 1950 in Aarhus, Denmark) is a computer scientist and the College of Engineering Chair Professor of Computer Science at Texas A&M University. ...

External links


  Results from FactBites:
 
Const Correctness - C++ Tutorials - Cprogramming.com (2274 words)
For instance, const references allow you to specify that the data referred to won't be changed; this means that you can use const references as a simple and immediate way of improving performance for any function that currently takes objects by value without having to worry that your function might modify the data.
Once you have a const object, it cannot be assigned to a non-const reference or use functions that are known to be capable of changing the state of the object.
Although returning a const reference prevents anyone from changing the data by using it, it means that you have to have persistent data to back the reference--it has to actually be a field of the object and not temporary data created in the function.
/* Rambling comments... */: Const correctness (1409 words)
Using const correctly and consistently means that when you look at a piece of code you can be certain that some types are not modified by the code that you're looking at or by code it calls.
Being const correct means you need to think a little bit more when you write the code but you can trade that for thinking a little bit less when you read the code.
Correct use of const tends to drive a design in the right direction; if some of the code needs to modify an object and some of the code doesn't then const will help you factor the code appropriately by building walls between areas of code that operate in different ways.
  More results at FactBites »


 
 

COMMENTARY     


Share your thoughts, questions and commentary here
Your name
Your comments

Want to know more?
Search encyclopedia, statistics and forums:

 


Lesson Plans | Student Area | Student FAQ | Reviews | Press Releases |  Feeds | Contact
The Wikipedia article included on this page is licensed under the GFDL.
Images may be subject to relevant owners' copyright.
All other elements are (c) copyright NationMaster.com 2003-5. All Rights Reserved.
Usage implies agreement with terms, 1022, m