博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C++之 const
阅读量:6000 次
发布时间:2019-06-20

本文共 2116 字,大约阅读时间需要 7 分钟。

hot3.png

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 
#include 
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的值无法发生改变,程序报错。

转载于:https://my.oschina.net/donngchao/blog/527377

你可能感兴趣的文章
Ubuntu 16.04系统下CUDA8.0配置Caffe教程
查看>>
Redis.py客户端的命令总结【二】
查看>>
linux shell 数组的使用
查看>>
CSS Sprites
查看>>
10进制转化成2进制,16进制
查看>>
markdown 语法汇总
查看>>
自动登录
查看>>
11.表达式语言
查看>>
3.数据校验和SpringEL
查看>>
面向对象编程-何为对象
查看>>
微信公众平台开发文摘
查看>>
OAF_OAF控件系列1 - Region Type汇总(概念)
查看>>
SPSite, SPWeb Dispose and Class Design Partter
查看>>
品尝阿里云容器服务:初步尝试ASP.NET Core Web API站点的Docker自动化部署
查看>>
alter table添加表约束
查看>>
C# 模拟提交 Form表单的数据
查看>>
shell脚本加密
查看>>
java二维数组求每行最大值,每列最小值,及输出数组主对角线上的元素
查看>>
java代码包装类----------Integer
查看>>
python(56):正则表达式积累
查看>>