Const (computer programming): Difference between revisions

Content deleted Content added
External links: Deleted several links which have basically identical content to other links by more prominent authors.
No edit summary
Line 1:
'''<code>Const<code>-correctness''' is a feature of some [[computer]] [[programming language feature]]s that allows the programmer to indicate when an object candoes or anddoes cannotnot change by declaring the object <code>const</code> (or non-<code>const</code>). It can be used to improve [[encapsulation]], correctness, readability, and even performance. The best known language with this feature is [[C plus plus programming language|C++]].
 
When a <code>const</code> object is used, the compiler will do its best to prevent the object from being changed, which allows programmers to utilize a simple form of [[design by contract|design contract]]. The idea of <code>const</code>-ness does not imply that the variable as it is stored in the [[computer]]'s [[computer storage|memory]] is unwriteable. Rather, <code>const</code>-ness is a compile-time construct that indicates what a programmer ''may'' do, not necessarily what he ''can'' do. (Of course, if an object resides in a [[Read-only memory|ROM]], then it is physically unwriteable regardless of its <code>const</code>-ness from the perspective of the [[compiler]].)
Line 107:
};
void Foo( S 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
*s.ptr = 0i; // Ok: the data pointed to by ptr is always mutable,
// even though this is usually not desirable
}
Line 139:
// contains a memory address for us to deference
const int * volatile const tableLookup = reinterpret_cast<int*>( 0x8004 );
 
tableLookup = &currentTableValue; // Error: cannot modify a const pointer
 
int currentTableValue = *tableLookup; // Deference the memory ___location
int newTableValue = *tableLookup; // Deference it again
 
tableLookup = &currentTableValue; // Error:! cannot modify a const pointer
 
</code>