当前位置:网站首页>const、volatile和restrict的作用和用法总结
const、volatile和restrict的作用和用法总结
2022-07-05 00:27:00 【金士顿】
const
const(constant)关键字可修饰变量、函数参数、返回值或函数体。
定义只读变量。
限制函数参数。防止意外修改。增加程序安全性和可靠性。
如const char *p表示,p指针指向的值不可更改,就是这个指针不能用来修改数据
如char *const p表示,p指针指向的地址不可更改
如const int arr[]则数组内的值都不能修改
const char *const p表示,所指向的数值和地址都不能变
const double locked[4]
double *pc=rates
pc=locked这句是非法的。因为locked是不能修改的
源文件中使用const int i = 1则在其他文件中应使用extern const int i,如在头文件中则应用static const int i = 1,因为各文件中需要包含这个头文件,需要static保证内部性。但如果用此方法存储数组,因为各个文件都需要创建这个静态数组,可能会占用较多的存储空间,需要从更多方面去考虑它的利弊。
volatile
volatile限定词则表示变量除了可被程序修改外还可能被外部代理修改,如变量保存当前的时钟时间。
编译器优化编译时会把不变的值放在寄存器,以供读取,标记volatile可以保证不被放入寄存器。
如不能被程序改变而能被代理改变则const volatile int i。
restrict
restrict只能用于指针int* restrict ptr,这样就使得ptr是指向某数据块的唯一方式。
可防止数据被其他指针操作。如在memcpy中为防止有重叠区域,采用restrict修饰传入的指针。同时,restrict也有利于编译器优化。
作者:胡哈哈哈
链接:https://www.jianshu.com/p/58f618bd9ea3
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
边栏推荐
- JS how to realize array to tree
- ORB(Oriented FAST and Rotated BRIEF)
- 《论文笔记》Multi-UAV Collaborative Monocular SLAM
- Upload avatar on uniapp
- go踩坑——no required module provides package : go.mod file not found in current directory or any parent
- 企业应用业务场景,功能添加和修改C#源码
- JS convert pseudo array to array
- lambda expressions
- leetcode518,377
- lambda表达式
猜你喜欢
lambda表达式
Application of fire fighting system based on 3D GIS platform
It's too convenient. You can complete the code release and approval by nailing it!
P3304 [SDOI2013]直径(树的直径)
青海省国家湿地公园功能区划数数据、全国湿地沼泽分布数据、全国省市县自然保护区
【路径规划】RRT增加动力模型进行轨迹规划
Verilog tutorial (11) initial block in Verilog
Continuous modification of business scenario functions
Get to know ROS for the first time
JS how to realize array to tree
随机推荐
Hash table, hash function, bloom filter, consistency hash
P4281 [AHOI2008]紧急集合 / 聚会(LCA)
What is the difference between port mapping and port forwarding
abc 258 G - Triangle(bitset)
Using fast parsing intranet penetration to realize zero cost self built website
[论文阅读] TUN-Det: A Novel Network for Thyroid Ultrasound Nodule Detection
AcWing164. 可达性统计(拓扑排序+bitset)
Is it safe to open and register new bonds? Is there any risk? Is it reliable?
【雅思阅读】王希伟阅读P4(matching1)
Go step on the pit - no required module provides package: go mod file not found in current directory or any parent
青海省国家湿地公园功能区划数数据、全国湿地沼泽分布数据、全国省市县自然保护区
Acwing164. Accessibility Statistics (topological sorting +bitset)
How to avoid arc generation—— Aafd fault arc detector solves the problem for you
1189. Maximum number of "balloons"
电力运维云平台:开启电力系统“无人值班、少人值守”新模式
IELTS examination process, what to pay attention to and how to review?
如何有效对直流列头柜进行监测
ORB(Oriented FAST and Rotated BRIEF)
Tester's algorithm interview question - find mode
积分商城游戏设置的基本要点