当前位置:网站首页>Functions and differences between static and Const
Functions and differences between static and Const
2022-07-03 21:36:00 【weixin_ forty-seven million two hundred and fifty-seven thousan】
const The defined constant is beyond its Scope Then its space will be released , and static The defined static constant does not release its storage space after the function is executed .
Let's start with static.
static There are three main functions :
1. Modify local variables , Become a static local variable
2. Modify global variable , Become a static global variable
3. Modify function , Become a static function
Let's explain... One by one .
1. Modify local variables . Become a static local variable
Let's first look at the following program :
#include<stdio.h>
void test()
{
int a = 5;
a++;
printf("%d", a);
}
int main()
{
int i = 0;
while (i < 10)
{
test();
i++;
}
}
What's the output ?
We see that a loop of the main function is a loop 10 Time test function , And then every time you execute test, They all print it once a,a from 6 Every time at first +1( because a++ in front , So from 6 Start ).
So the result should be 6 7 8 9 10 11 12 13 14 15
Is the result as we thought ?
Let's take a look at the results :
this ...? It doesn't seem to accord with our conjecture .
Why does it show up 10 individual 6 Well ?
Let's think about it , Then we can roughly know the problem .
Every time you enter the cycle a It's all reset , So it won't be added all the time .
Why is that ?
because a Is a temporary variable we created , It will be destroyed as the function ends , Next time I come in , Will be recreated .
So it will cause the result we just had .
Then we have to output that 6-15 What should we do with such a result ?
We can do it in test In the function int Add a... To the front static
In this way, this local variable will not be destroyed with the end of the function , The principle will be explained later
Changed to the following :
void test()
{
static int a = 5;
a++;
printf("%d ", a);
}
So let's run it again , Let's see the result
It is in line with our conjecture .
Then why is it exactly like this ? Here we will talk about the three areas where data is stored in memory
The stack area Heap area Static zone
The stack area : Where local variables and function parameters are stored . The memory allocated by the stack area will be automatically recycled after the scope of the stack area passes , There's no need to manually manage .
Heap area : By, for example malloc,realloc The memory actively applied for by such functions , After use, use free Free memory , If you forget to release memory after application , It is easy to cause memory leakage .
Static zone : The area where static variables and global variables are stored , Once the memory of the static area is allocated , It will not be released until the program is completed .
Static area, in other words : The life cycle of the static area is the same as that of the program , Out of the scope of action, it will not be destroyed ( above static int a =5) This example , Equivalent to the same scope of action , But the life cycle has been extended .
Then we can also explain the principle in the above example :
static When modifying a local variable , What actually changes is the storage location of the variable , Originally in the stack area , After being decorated, it is placed in the static area .
So it won't be destroyed except for the scope of action .
2.static Modify global variable
Now? vs Two source files are created in the compiler :test1.cpp,test2.cpp
Let's start with the document test1.cpp Create a global variable , as follows :
Then , We know that referencing global variables in other files requires extern This function , So let's do it again test2.cpp This global variable is referenced in this file .
Let's see the output :
Perfect output of external files .
But if we test1.cpp Add static, We can see if the program can run successfully .
We run this program :
There's something wrong with the program .
We look at the wrong reasons : Unresolved external symbols .
Why is that , We have already used extern This function calls the global variable in the external file , Why can't it be parsed ?
That must be static Damn it , What role does it play here ?
A global variable originally has external attributes , But be static After modification , The external attribute becomes the internal connection attribute , It can only be used in its own source file , Cannot be used in other files .
So what? , By static The modified global variable gives us the feeling that the scope has become smaller ( It can only be used inside your own file , Cannot be used in other documents ), But the essence is that the link attribute has changed .
3.static Modify function
This is similar to the one that modifies global variables .
Or create two source files test1.c、test2.c.( The file name suffix is .c, No .cpp, stay c++ This effect cannot be seen in the environment )
We are test1.cpp The following program is written in the file :
And then we were in test2.c It says in it Add Function content .
result :
Perfect output of the results we want .
But if we were here test2.c Inside Add Add... To the function static:
Run again :
An error occurred .
The cause of the error is also an unresolved external symbol .
Wrong , The same as the last modification of global variables :
A function originally has external connection properties , But be static After modification , The external link attribute becomes the internal link attribute , You can only use it inside your own source file , Can't be used inside other files .
Let's talk about it again const
If you put const Put in front of the variable type name , It shows that the value of this variable remains unchanged , This variable must be initialized at definition , Any assignment to it after initialization is illegal .
1.const Modify the constant
for example :
int a=5;
a=6;
here a The value of is modified to 6.
const int a=5;
Now the variable a The value of can be modified
If you still write a=6, Then the program will make an error .
2.const Decorate constant static string
for example :
const char* str="fdsafdsa";
without const Modification of , We may write in the back intentionally or unintentionally str[4]=’x’ Such a statement , This will result in the assignment of read-only memory areas , Then the program will immediately terminate abnormally . With const, This error can be detected as soon as the program is compiled , This is it. const The benefits of . Let logic errors be found at compile time .
3. Modify the parameters of the function
Direct examples to illustrate :
1. Prevent the pointer from modifying the content pointed to by the pointer
Let's write the following function
void String(char* str1,const char* arr2);
This time we can in String This function is modified arr1 Content , But if you modify arr2 The program will report an error , here arr2 Can no longer be modified .
or :
2. Prevent the pointer from modifying the address pointed to by the pointer
void Swap(int* const p1,int* const p2);
here p1 and p2 The address pointed to can no longer be modified .
That's all static and const The general difference between , Of course, there will be many omissions , Welcome to add !
边栏推荐
- Last week's content review
- Redis data migration (II)
- Capture de paquets et tri du contenu externe - - autoresponder, composer, statistiques [3]
- Quickly distinguish slices and arrays
- MySQL——idea连接MySQL
- Dahua series books
- What is the maximum number of concurrent TCP connections for a server? 65535?
- Redis concludes that the second pipeline publishes / subscribes to bloom filter redis as a database and caches RDB AOF redis configuration files
- Nmap and masscan have their own advantages and disadvantages. The basic commands are often mixed to increase output
- Common SQL sets
猜你喜欢
Dahua series books
使用dnSpy对无源码EXE或DLL进行反编译并且修改
Redis data migration (II)
Hcie security Day12: supplement the concept of packet filtering and security policy
The post-90s resigned and started a business, saying they would kill cloud database
MySQL——JDBC
Selenium has three waiting methods (forced waiting, implicit waiting, and display waiting)
Summary of common operation and maintenance commands
Décompiler et modifier un exe ou une DLL non source en utilisant dnspy
抓包整理外篇——————autoResponder、composer 、statistics [ 三]
随机推荐
Kubernetes 通信异常网络故障 解决思路
Après 90 ans, j'ai démissionné pour démarrer une entreprise et j'ai dit que j'allais détruire la base de données Cloud.
The 12th Blue Bridge Cup
QFileDialog
MySQL——JDBC
How to choose cache read / write strategies in different business scenarios?
Great gods, I want to send two broadcast streams: 1. Load basic data from MySQL and 2. Load changes in basic data from Kafka
Global and Chinese market of telematics boxes 2022-2028: Research Report on technology, participants, trends, market size and share
[vulnhub shooting range] impulse: lupinone
UI automation test: selenium+po mode +pytest+allure integration
Memory analyzer (MAT)
Kernel symbol table
Getting started with postman -- built-in dynamic parameters, custom parameters and assertions
Summary of common operation and maintenance commands
C程序设计的初步认识
Idea shortcut word operation
MySQL——idea连接MySQL
Solve the problem that openocd fails to burn STM32 and cannot connect through SWD
Minio deployment
Compilation Principle -- syntax analysis