当前位置:网站首页>On the corners of const
On the corners of const
2022-06-21 10:36:00 【Longcheng deficit】
About const In every corner of the world
const Keyword provides auxiliary reference information for program robustness and compilation optimization .
const It is mainly interpreted and used by the compiler , It's a static concept . That is to say , When we pass a variable const When the description is constant , Subsequent modifications to this variable , Will be checked by the compiler , Then an error .
however , Once the inspection is passed , In actual operation , It is no different from ordinary variables . such as , If we get the address of the constant by other means , You can also change its value at run time . In the memory , It is still represented as a common data variable .
const There are many descriptive articles on the Internet . Authoritative interpretation , Personally, I think it should be the standard description . The compiler shall comply with the standard requirements , For the const Carry out inspection and treatment .
const You can modify variables and functions .
Modifying variables , It can be a built-in type , It can also be a custom type .
The built-in type can be a normal variable , It can also be a pointer variable , It can also be a reference .
Modify function , You can modify the return value of a function , The parameters of the function , The function itself .
The function can be C function , It can be C++ The function in ,C++ Including static functions and member functions .
Modification of the return value and parameters of a function , Personal understanding is based on the modification of variables , Many places can be understood by referring to the modification of variables .
Modification of the function itself , Mainly for C++ in , In fact, it is decorated this The pointer . such , We understand const Member variables cannot be modified in a function , Just a simple . otherwise , Simply memorize by rote , The effect is not good .
Here we mainly look at the modification of the function return value . To elicit questions , Let's start with a few simple examples :
Decoration of common built-in types , such as
int const cint1 = 1;
const int cint2 = 2;
The compiler will require an initial value when defining , And elsewhere in the code , You can only quote , Can't change value , Otherwise it will go wrong . Same as before , These are all compilation checks .
For the above two ways , Compilers seem to be all about const Variable to handle , There is no difference . This point , You'll see that in the back . Let me first mention .
however , For pointer variables , The above two ways of writing are different
int * const cpi1 = &xx;
const int * cpi2;
Assign values when the first one needs to be defined , Otherwise the compiler will tell you constants cpi1 Not initialized . therefore , here cpi1 Is a constant , Is not a variable , The point should be clear from the beginning .
The second one can be compiled through , explain cpi2 It's a variable , Is not a constant . however , If you try to assign a value to the content it points to , Error will be reported in compilation , Tips *cpi2 Is a constant , That is, the content pointed to by the pointer is a constant .
Because this article is to study const In every corner of the world , So let's see const Put it in the middle :
int const * cpi3;
actually , This kind of writing is rare , It's a little nondescript , The compiler presses cpi2 Handle it the same way .
below , Let's see. const Decorating functions .
For common built-in types , We can rely on intuition , Write the following example :
const int func();
however , Similar to variables , There are also the following possibilities :
int const func();
As I said before , Modification of the function itself , Is placed after the function , That is, something like this ,int func() const, So here are all decorated return values .
In order to see the difference between the above two ways , We make mistakes , Let the compiler tell us where the error is , Through error messages , Further judge the difference .
How to make mistakes ?
There is a way , We declare a function pointer , Then define a function , Let the function pointer point to the function , If the two definitions are inconsistent , Error will be reported when compiling , Here is the starting point .
typedef const int (*pfunc)();
const int getVal2() {return 123;}
pfunc xxx;
xxx = getVal2;
Because the above types are consistent , So compile through , We will declare that const Get rid of , have a look
typedef int (*pfunc)();
Compiler error
invalid conversion from ‘const int (*)()’ to ‘pfunc {aka int (*)()}’
We will define the const Move , have a look
The compiler reported the same error
invalid conversion from ‘const int (*)()’ to ‘pfunc {aka int (*)()}’
This shows two ways of writing , There is no difference in the compiler's view .
Okay , We replace the basic built-in type with a pointer , See what happens
const int * getVal2() {return &g_var;}
The compiler error is as follows :
invalid conversion from ‘const int* (*)()’ to ‘pfunc {aka int (*)()}’
take const Change the position ,
int const * getVal2() {return &g_var;}
invalid conversion from ‘const int* (*)()’ to ‘pfunc {aka int (*)()}’
Errors do not change , This is consistent with the pointer variable situation described above
Let's see ,const Put it in * What happened later
int * const getVal2() {return &g_var;}
Compiler error changed ,
invalid conversion from ‘int* const (*)()’ to ‘pfunc {aka int (*)()}’
These three ( There are essentially two kinds of ) What are the differences in writing ?
For the first and second , That is to say const In the previous case ,
int * presult = getVal2();
This writing method will report compilation errors ,invalid conversion from ‘const int*’ to ‘int*’
It returns a pointer , The data pointed to by the pointer is a constant , Do not modify , The lvalue also needs to be a pointer of the same type .
For the third way of writing , The above lvalue compilation will not be a problem .const Decorated function name , The function name itself is not modifiable , So this way of writing should be meaningless .
But the compiler will check the decoration , Where relevant , Must be of the same type .
Other uses ? To be added .
边栏推荐
- 给电脑加装固态
- TC software detailed design document (mobile group control)
- Embedded software project process and project startup instructions (example)
- Audio and video format introduction, encoding and decoding, audio and video synchronization
- Odd number of characters异常
- EIG和沙特阿美签署谅解备忘录,扩大能源合作
- Telecommuting Market Research Report
- Versions supported by vuforia engine
- Are you still using localstorage directly? The thinnest in the whole network: secondary encapsulation of local storage (including encryption, decryption and expiration processing)
- 应用配置管理,基础原理分析
猜你喜欢

Les nouveaux programmeurs optimisent une ligne de code lundi et sont exhortés à se retirer mercredi?

The first phase of takin open source training camp is coming! Teach you to complete the full link voltage test hand in hand!

Optimisation des performances - compression, chargement et formatage des images

New year's Eve, are you still changing the bug?

DSP online upgrade (2) -- design framework of bootloader

Matplotlib 绘制圆环图的两种方法!

New programmers optimize a line of code on Monday and are discouraged on Wednesday?

Haplotype analysis using shapeit

character string

Huawei releases wireless innovative products and solutions to build 5gigaverse Society
随机推荐
音视频同步你一定要注意的知识点:
如何做一个有趣的人
Es composite query workload evaluation
Will the thunderstorm of Celsius be the "Lehman moment" in the field of encryption?
中国国际电子商务中心与易观分析联合发布:2021年4季度全国网络零售发展指数同比增长0.6%
Haplotype analysis using shapeit
异常
开课报名|「Takin开源特训营」第一期来啦!手把手教你搞定全链路压测!
Mythical Games宣布与韩国领先游戏发行商Kakao Games合作,推动亚太区业务扩张
Three elements of basic concepts and methods of machine learning
DSP online upgrade (4) -- functions implemented by bootloader
Starting a prairie fire, Alibaba cloud database "hundred cities gather together" to help small and medium-sized enterprises' digital intelligence transformation
Financial institutions scramble for "digital employees"; Release of aging service evaluation framework for insurance app
Underlying principle of Concurrency: thread, resource sharing, volatile keyword
Embedded software project process and project startup instructions (example)
New programmers optimize a line of code on Monday and are discouraged on Wednesday?
Introduction and template of segment tree Foundation (I)
One line of code accelerates sklearn operations thousands of times
The "first city" in Central China. How can Changsha be built?
获取配置文件properties中的数据