In the C, C++, and D programming languages, const is a type qualifier, a keyword applied to a data type that indicates that the data is constant (does not vary). While this can be used to declare constants, const in the C family of languages differs from similar constructs in other languages in being part of the type, and thus has complicated behavior when combined with pointers, references, composite data types, and type-checking.
const was introduced by Bjarne Stroustrup in C with Classes, the predecessor to C++, in 1981, and was originally called readonly.As to motivation, Stroustrup writes:
"It served two functions: as a way of defining a symbolic constant that obeys scope and type rules (that is, without using a macro) and as a way of deeming an object in memory immutable."
The first use, as a scoped and typed alternative to macros, was analogously fulfilled for function-like macros via the inline keyword. Constant pointers, and the * const notation, were suggested by Dennis Ritchie and so adopted.
const was then adopted in C as part of standardization, and appears in C89 (and subsequent versions) along with the other type qualifier, volatile. A further qualifier, noalias, was suggested at the December 1987 meeting of the X3J11 committee, but was rejected; its goal was ultimately fulfilled by the restrict keyword in C99. Ritchie was not very supportive of these additions, arguing that they did not "carry their weight", but ultimately did not argue for their removal from the standard.
D subsequently inherited const from C++, where it is known as a type constructor (not type qualifier) and added two further type constructors, immutable and inout, to handle related use cases.
#include <iostream>
#include <stdlib.h>
using namespace std;
void fun(const int &a, const int &b);
int main(void)
{
int x = 3;
int y = 5;
fun(x, y);
cout << x << "," << y << endl;
system("pause");
return 0;
}
void fun(const int &a, const int &b)
{
a = 10;
b = 20;
}
以上的程序之所以运行时报错,就是因为const关键字的限定,使得函数的形参无法改变实参的原来的值,从而在其他的程序设计中避免了误操作的发生。在本例中a,b的值无法发生改变,程序报错。
来源:oschina
链接:https://my.oschina.net/u/2392809/blog/527377