当前位置:网站首页>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
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
边栏推荐
- C语言中sizeof操作符的坑
- Hash table, hash function, bloom filter, consistency hash
- 22-07-02周总结
- Fast parsing intranet penetration helps enterprises quickly achieve collaborative office
- A new method for analyzing the trend chart of London Silver
- Actual combat simulation │ JWT login authentication
- OpenHarmony资源管理详解
- Power operation and maintenance cloud platform: open the new mode of "unattended and few people on duty" of power system
- Parsing of XML
- 人脸识别5- insight-face-paddle-代码实战笔记
猜你喜欢

Application of fire fighting system based on 3D GIS platform

Learn C language from scratch day 024

Using the uniapp rich text editor
Date time type and format in MySQL

【雅思阅读】王希伟阅读P3(Heading)

Learning of basic amplification circuit

Significance of acrel EMS integrated energy efficiency platform in campus construction

Leetcode70 (Advanced), 322

电力运维云平台:开启电力系统“无人值班、少人值守”新模式

js如何实现数组转树
随机推荐
P3304 [SDOI2013]直径(树的直径)
Using the uniapp rich text editor
积分商城游戏设置的基本要点
Build your own minecraft server with fast parsing
城市轨道交通站应急照明疏散指示系统设计
The pit of sizeof operator in C language
P4281 [ahoi2008] emergency assembly / gathering (LCA)
P4408 [NOI2003] 逃学的小孩(树的直径)
How to use fast parsing to make IOT cloud platform
22-07-02周总结
[IELTS reading] Wang Xiwei reading P3 (heading)
Detailed explanation of openharmony resource management
如果炒股开华泰证券的户,在网上开户安全吗?
Go step on the pit - no required module provides package: go mod file not found in current directory or any parent
Hash table, hash function, bloom filter, consistency hash
2022.07.03(LC_6108_解密消息)
2022.07.03(LC_6111_统计放置房子的方式数)
Paper notes multi UAV collaborative monolithic slam
(脚本)一键部署redis任意版本 —— 筑梦之路
挖财学院开户安全的吗?开户怎么开?