当前位置:网站首页>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 .
边栏推荐
- There are various signs that apple is expected to support AV1
- Classic examples of C language - use 4 × The matrix displays all integers from 1 to 16 and calculates the sum of each row, column, and diagonal
- English grammar_ Demonstrative pronoun - so
- 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
- Docker pulls the redis image and runs it
- Flutter | firstwhere error reporting
- Pytest interface automated testing framework | how to get help
- Gbase 8C session information function (III)
- CA digital certificate
- Redis persistence mechanism RDB, AOF
猜你喜欢

Intelligent OCR identification of express documents helps the logistics industry to upgrade Digitalization

Delete all data of specified query criteria in Oracle

Inftnews | protect the "Snow Mountain Spirit", and the 42verse "digital ecological protection" public welfare project is about to start

What are blue-green deployment, Canary release and a/b test

二叉搜索树的简易实现及剖析

【电赛训练】非接触物体尺寸形态测量 2020年电赛G题

数据标准详细概述-2022

English grammar_ Demonstrative pronoun - so

php实现 Stripe订阅

XXL job realizes the code parsing of email sending warnings (line by line code interpretation)
随机推荐
Redis数据结构
Application of SCA on devsecops platform
Pytest interface automation test framework | summary
Redis master-slave synchronization mechanism
Gbase 8C access authority query function (V)
Summary of polynomial commitment schemes
mongodb的多数据源配置
Development of main applet for business card traffic near the map
Detailed overview of data standards -2022
Method of C language annotation
GBase 8c系统表信息函数(二)
GBase 8c 访问权限查询函数(一)
Classic examples of C language switch case statement conversion date format
July 23, 2022 - mapper file description
Gbase 8C session information function (6)
Educational Codeforces Round 132 (Rated for Div. 2)(A-D)
Docker builds sonarqube, mysql5.7 environment
Pytest interface automation testing framework | multi process running case
Classic example of C language - loan balance
GBase 8c 字符串操作符