当前位置:网站首页>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# 案例简单变量运算

Skills in analyzing the trend chart of London Silver

OpenHarmony资源管理详解

Build your own minecraft server with fast parsing

Continuous modification of business scenario functions

leetcode494,474

Ap8022 switching power supply small household appliances ACDC chip offline switching power supply IC

Consolidated expression C case simple variable operation

In June, the list of winners of "Moli original author program" was announced! Invite you to talk about the domestic database
随机推荐
Two numbers replace each other
人脸识别5- insight-face-paddle-代码实战笔记
How to use fast parsing to make IOT cloud platform
Detailed explanation of openharmony resource management
[paper reading] cavemix: a simple data augmentation method for brain vision segmentation
Five papers recommended for the new development of convolutional neural network in deep learning
P3304 [SDOI2013]直径(树的直径)
Continuous modification of business scenario functions
Date time type and format in MySQL
Daily practice (18): stack containing min function
Distributed base theory
[Peking University] tensorflow2.0-1-opening
ORB(Oriented FAST and Rotated BRIEF)
[paper reading] Tun det: a novel network for meridian ultra sound nodule detection
Fast analysis -- easy to use intranet security software
Basic points of the game setup of the points mall
P4281 [AHOI2008]紧急集合 / 聚会(LCA)
初识ROS
A new method for analyzing the trend chart of London Silver
How to do the project of computer remote company in foreign Internet?