当前位置:网站首页>C language: deep analysis of const keyword
C language: deep analysis of const keyword
2022-07-24 00:32:00 【Tiger Taro's inheritance】
const It's a C Language (ANSI C) Key words of , Has a pivotal position . It defines a variable that cannot be changed , Produce a static effect . Use const To some extent, it can improve the security and reliability of the program . in addition , When watching other people's code , Understand clearly const What it does , It is also helpful to understand each other's procedures . in addition CONST It also appears in other programming languages , for example Pascal、C++、PHP5、B#.net、HC08 C、C# etc. .
Catalog
1. Definition
const The type of decoration is the pointing type , The value of a constant type variable or object cannot be updated .
2. Purpose
const The initial purpose of keyword launch , To replace precompiled instructions , Eliminate its shortcomings while inheriting the advantages of precompiled instructions .
3. effect
1. Can define const Constant , Have no variability
2. Easy to type check , Let the compiler know more about processing , Eliminated some hidden dangers .
3. It can avoid the appearance of fuzzy numbers , It is also convenient to adjust and modify parameters . Same as macro definition , If it can be done, it will not change , Change all the time !
4. Can protect things that are decorated , Prevent accidental modification , Enhance the robustness of the program .
5. You can save space , Avoid unnecessary memory allocation .
6. Improved efficiency
3.1const Modifying variables
Usually we write an integer variable a, We can change by assignment a The corresponding value , If we add one in front of it const What will happen ?


like this , In the face of const An error will be reported when modifying variables to assign values .
So we can come to a conclusion :const Decorated variable , Cannot be modified directly .
But there is no way to change the value of variables , We can introduce and modify variables through pointers a
#include<stdio.h>
int main()
{
const int a = 0;
int* p = &a;// Defining pointer variables p To hold the a The address of
printf(" Before the change :%d\n", a);
*p = 20;// Give... By dereferencing a assignment
printf(" After change :%d\n", a);
return 0;
}

This shows that const Variables can be modified indirectly .
that const What's the use of this keyword ?
effect :
- Let the compiler do modified checks ( Grammar detection ).
2. Tell the code reader not to change this variable , It's one of them ” Self describing meaning “.( At the grammatical level, the relatively weak binding effect ).
that const Can the decorated variable be part of the array ?
Conclusion :const Decorated variables cannot be part of an array .
3.2const Modify the array
const Modify the array , and const Modifier constants are the same , Array elements cannot be assigned twice , Let's look at a piece of code :
When we define a const Decorated array , When it is assigned twice , compiler , An error has occurred .
int const a[5] = {
1, 2, 3, 4, 5};
count int a[5] = {
1, 2, 3, 4, 5};
// These two arrays are essentially no different .
//const No matter what int In fact, both the left and the right are ok .
// But we are usually used to const Put it on the left side. .
3.3const Modify a pointer
First, let's understand the difference between pointer and pointer variable :
1. The pointer is the address .
2. Pointer variables are used to store addresses .

Constant pointer :
The value of the variable pointed to by the pointer cannot be modified through the pointer . But pointers can point to other variables .

pointer to const ( constant pointer ):
The value of a pointer constant cannot be modified , That is, you cannot save a new address , Cannot point to other variables . But you can modify the value of the variable it points to through the pointer .
Here we give a more common example to deepen our understanding :
If p It's a girl ,m It's the boy 1,n It's the boy 2, Now the boy 1 Yes 10 Yuan , The boy 2 Yes 100 Yuan , Girls are boys 1 My girlfriend , So there is int *p = &m; But boy 1 Don't want girls to spend their money , So he int const *p = &m; So the girl can't spend the boy's money to make *p = 0 了 ; The girl p Think boys 1 Too tight , So with the boy 1 break up , Choose a boy 2 Be your girlfriend , So there is p = &n; This is OK .
This time the boy 1 Panic again , You can't change your boyfriend , So he just int * const p = &m; So he allows the girl to spend his money * p = 0; But you can't change your boyfriend p = &n;
And then one day , The boy 1 Another idea :int const * const p = &m; At this time, the girl can't spend money , You can't change your boyfriend .
If you still don't understand , You can go to b Take a look at brother bitpeng's explanation of this part of knowledge : link : Brother bitpeng said const Modifier pointer is an example of popular understanding
stay 90P Of 46:56 At the time of , You can jump to study !
3.4const Modify function
3.4.1.const Modifies the function parameter
const Modifiers can also modify the parameters of a function , When you don't want this parameter value to be accidentally changed in the function body, you can use const To modify .
const int fun(const int a)const;
#include<stdio.h>
void fun(const int* p)// add const Modifier means a Can't be changed directly
{
printf("%d\n", *p);
*p = 20;// Report errors , because const modification a Cannot be changed directly
}
int main()
{
int a = 0;
int* p = &a;
fun(p);// Call function
return 0;
}

3.4.2.const Decorated return value
const Modifiers can also modify the return value of a function , The return value cannot be changed .
边栏推荐
- How to open a low commission account? Is it safe?
- Gbase 8C session information function (III)
- Classic example of C language - commodity inspection code
- 【电赛训练】非接触物体尺寸形态测量 2020年电赛G题
- GBase 8c 会话信息函数(三)
- PayPal subscription process and API request
- Simple implementation and analysis of binary search tree
- 如何提升数据质量
- [wechat applet] design and interactive implementation of auction product details page (including countdown and real-time update of bids)
- Jenkins uses sonarqube to build pipeline code review project
猜你喜欢

How to realize 485 wireless communication between multiple sensors and Siemens PLC?

理解多态,让不同的“人”做同一件事情会产生不同的结果

English语法_指示代词 -such / the same

数据标准详细概述-2022

Coloring old photos - deoldify get started quickly

EFCore高级Saas系统下单DbContext如何支持不同数据库的迁移

Blockbuster | certik: Web3.0 industry safety report release in the second quarter of 2022 (PDF download link attached)

Multi data source configuration of mongodb

Problem note - unable to open include file: "direct.h": no such file or directory

Redis cluster hash sharding algorithm (slot location algorithm)
随机推荐
mongodb的多数据源配置
Delete all data of specified query criteria in Oracle
GBase 8c 会话信息函数(三)
Unity metaverse (I). Ready player me & blender customize your Avatar
Redis data structure
Gbase 8C string Operator
二叉搜索树的简易实现及剖析
数据模型设计方法概述
Classic example of C language - find the minimum number of banknotes
What are blue-green deployment, Canary release and a/b test
Redis主从同步机制
Educational Codeforces Round 132 (Rated for Div. 2)(A-D)
The prediction of domestic AI protein structure reproduced a breakthrough and solved the 3D structure with a single sequence. Peng Jian's team: "the last piece of puzzle since alphafold2 has been comp
English语法_指示代词 -such / the same
EFCore高级Saas系统下单DbContext如何支持不同数据库的迁移
Beifeng communication appeared in China (Xiamen) emergency exhibition | intelligent communication means are strong and eye-catching!
泛型机制和增强for循环
采坑websocket总结
docker 拉取redis镜像 并运行
Codeforces Round #807 (Div. 2)(A-D)