当前位置:网站首页>Const understanding one
Const understanding one
2022-06-23 04:48:00 【Boundless also initial heart】
Always want to understand clearly const Usage of , I have a good look these days , The following is a simple and easy to understand article I found on the Internet , Specially recorded here . however , There are also some arguments worth discussing .
++++++++++++++++++++++++++++++++++++++++++++++++++++++
const stay C The language is a relatively new descriptor , We call this constant modifier , It means what it modifies
The object of is constant (immutable).
Let's see how it can be used grammatically .
1、 Modifying local variables inside functions .
example :
void func(){
const int a=0;
}
First , Let's put the const This word is ignored , that a It's a int Local automatic variables of type ,
We give it an initial value 0.
And then look at it const.
const As a type determiner , and int Have the same status .
const int a;
int const a;
It is equivalent. . So here we must clearly understand ,const Who is the object of decoration , yes a, and int no
It matters .const The object he modifies is required to be a constant , Cannot be changed , Cannot be assigned , Not as left value (l-value).
This is also wrong .
const int a;
a=0;
This is a very common use :
const double pi=3.14;
At the end of the program if an attempt is made to pi Another assignment or modification will result in an error .
Then look at a slightly more complicated example .
const int* p;
Let's get rid of it first const Modifier .
Be careful , The following two are equivalent .
int* p;
int *p;
In fact, what we want to say is ,*p yes int type . So clearly ,p It means pointing. int The pointer to .
Empathy
const int* p;
In fact, it's equivalent to
const int (*p);
int const (*p);
namely ,*p Is a constant . in other words ,p The data pointed to is a constant .
therefore
p+=8; // legal
*p=3; // illegal ,p The data pointed to is a constant .
So how to declare a pointer that is a constant itself ? The way is to let const As close as possible to p;
int* const p;
const On the right there is only p, obviously , It embellishes p, explain p Cannot be changed . And then put const Get rid of , Sure
See p It's a point int Pointers to formal variables .
therefore
p+=8; // illegal
*p=3; // legal
Let's take a more complicated example , It is a combination of the above two
const int* const p;
explain p I am a constant , And p The variable pointed to is also a constant .
therefore
p+=8; // illegal
*p=3; // illegal
const Another function is to modify the constant static string .
for example :
const char* name=David;
without const, We may write in the back intentionally or unintentionally name[4]=’x’ Such a statement , This will
Result in the assignment of read-only memory area , Then the program will immediately terminate abnormally . With const, This mistake is
It can be checked immediately when the program is compiled , This is it. const The benefits of . Let the logic error in the compilation
To be discovered .
const It can also be used to decorate arrays
const char s[]=David;
Similar to the above .
2、 Decorate parameters when a function is declared
Let's look at an example in practice .
NAME
memmove – copy byte string
LIBRARY
Standard C Library (libc, -lc)
SYNOPSIS
include
void *
memmove(void *dst, const void *src, size_t len);
This is a function in the standard library , Used to copy a string in bytes ( Memory ).
Its first parameter , Is where to copy the string (dest), It's the destination , This memory area must
It's writable .
Its second parameter , Is what kind of string to copy out , We only read this memory area
take , Don't write .
therefore , Let's look at this function from its own point of view ,src This pointer , The memory it points to
The stored data remains unchanged throughout the execution of the function . therefore src The content pointed to is a constant . So he
Need to use const modification .
for example , We use it here .
const char* s=hello;
char buf[100];
memmove(buf,s,6); // It should be used here strcpy or memcpy Better If we write the opposite ,
memmove(s,buf,6);
Then the compiler will report an error . The fact is that we often write the parameters of various functions in reverse order . The fact is that
Translator helped us a lot at this time . If the compiler silently does not report an error ,( Remove... From the function declaration
const that will do ), Then the program will crash when it runs .
Another point to note here is in the function parameter declaration const It is generally used to declare pointers rather than variables themselves .
for example , above size_t len, The function can be implemented without any change len Value , So whether
Should put the len It is also declared as a constant ? Sure , You can do that . Let's analyze the advantages and disadvantages of doing so .
If you add const, So for the implementer of this function , It can prevent him from repairing when implementing this function
Change the value that does not need to be modified (len), That's fine .
But for the user of this function ,
1. This modifier is meaningless , We can pass a constant integer or a non constant integer through
Go to , Anyway, what the other party got was just one we passed copy.
2. Exposes the implementation . I don't need to know if you've changed it when implementing this function len Value .
therefore ,const Generally, it is only used to decorate the pointer .
Let's look at another complex example
int execv(const char *path, char *const argv[]);
Focus on the following ,argv. What does it stand for .
If you remove const, We can see that
char * argv[];
argv Is an array , Every element of it is char * Pointer to type .
If you add const. that const Who are you decorating ? What he decorates is an array ,argv[], It means
Say that the elements of this array are read-only . So what is the type of the elements of the array ? yes char * Type refers to
The needle . That is, the pointer is a constant , And the data it points to is not .
therefore
argv[1]=NULL; // illegal
argv[0][0]=’a’; // legal
3、 Global variables .
Our principle remains , Use global variables as little as possible .
Our second rule It is , Use... As much as possible const.
If a global variable is used only in this file , So there is no difference between the usage and the function local variables mentioned above .
If it is to be shared among multiple files , Then there is a storage type problem involved .
There are two ways .
(1). Use extern
for example
/* file1.h */
extern const double pi;
/* file1.c */
const double pi=3.14;
Then others need to use pi Of this variable , contain file1.h
include file1.h
perhaps , Just copy that statement yourself .
The result is , After the whole program is linked , All required pi This variable shares a storage area .
(2). Use static, Static external storage classes
/* constant.h */
static const pi=3.14;
You need to use this variable *.c In file , Must contain this header file .
Ahead static Must not be less . Otherwise, the link will report that the variable has been defined multiple times .
The result is , Each contains constant.h Of *.c file , Each has its own version of the variable copy,
This variable is actually defined more than once , Takes up more than one storage space , But I added static keyword
after , Resolved the conflict of redefinition between files .
The downside is a waste of storage space , The linked executable becomes larger . But usually , This , Little
A change of a few bytes , Not a problem .
The advantage is , You don't care which file this variable is initialized in .
Last , say something const The role of .
const The benefits of , Is the introduction of the concept of constants , Let's not modify the memory that should not be modified . direct
The function is to make more logical errors found at compile time . So we should use as much as possible const.
But many people are not used to using it , What is more , In the whole program To write / debugging Only after that can we make up
const. If it's a complement to the declaration of a function const, fair . If it's for overall situation / Local variables complement const, that
Well …… that , It is too late , It just makes the code look more beautiful . About const Use , Once there was a
A joke says ,const It's like a condom , Remember in advance . If you don't remember to use it until you've finished it ,
ha-ha …… ha-ha ……
边栏推荐
- Monitoring artifact ZABBIX, from deployment to application, goes deep layer by layer
- Transformers中的动态学习率
- Pta:7-64 what day of the year is this day
- 自举驱动、top开关电源、光耦拾遗
- 【论文阅读】Semi-Supervised Learning with Ladder Networks
- QT elidedText 只对中文符合起作用,对英文不起作用的问题解决
- composer按装laravel
- OpenJudge NOI 1.13 51:古代密码
- STL教程3-异常机制
- Pta:6-30 time addition
猜你喜欢

电流继电器JDL-1002A

如何让社交媒体成为跨境电商驱动力?这款独立站工具不能错过!

一款MVC5+EasyUI企业快速开发框架源码 BS框架源码

如何解决独立站多渠道客户沟通难题?这款跨境电商插件一定要知道!

STL教程3-异常机制

McKinsey: in 2021, the investment in quantum computing market grew strongly and the talent gap expanded

If you want to understand PostgreSQL, you must first brush the architecture

#18生成器函数的参数传递

PCB----理论与现实的桥梁

在Pycharm中对字典的键值作更新时提示“This dictionary creation could be rewritten as a dictionary literal ”的解决方法
随机推荐
如何让社交媒体成为跨境电商驱动力?这款独立站工具不能错过!
关于php里tcp通讯用swoole框架出现的小问题
TS进阶之infer
Alkylation process test questions and simulation test in 2022
Transformers中的动态学习率
距离度量 —— 余弦距离(Cosine Distance)
② cocoapods原理及 PodSpec 文件上传操作
使用Live Chat促进业务销售的惊人技巧
PaddlePaddle模型服务化部署,重新启动pipeline后出现报错,trt报错
独立站聊天机器人有哪些类型?如何快速创建属于自己的免费聊天机器人?只需3秒钟就能搞定!
Abnova 荧光染料 510-M 链霉亲和素方案
Current relay hdl-a/1-110vdc-1
开关磁阻电机悬浮驱动IR2128小结
Bootstrap drive, top switching power supply and Optocoupler
Pta:6-71 clock simulation
电流继电器HDL-A/1-110VDC-1
Laravel中使用 Editor.md 上传图片如何处理?
大一学生课设c——服装管理系统
If you want to understand PostgreSQL, you must first brush the architecture
32单片机一个变量多个.c里使用