当前位置:网站首页>006 C language foundation: C storage class
006 C language foundation: C storage class
2022-06-27 04:24:00 【Prison plan progress 50%】
List of articles
One : summary
Storage classes are used to define C Program variable 、 The scope of the function ( visibility ) And life cycle . These specifiers are placed before the type they decorate .
Two : classification
Storage classes can be divided into :
auto
register
static
extern
3、 ... and :auto Storage class
auto The storage class is the default storage class for all local variables , The following example defines two variables with the same storage class , These two lines are equivalent ,auto It can only be used in functions , namely auto Only local variables can be modified .
{
int mount;
auto int mount2;
}
Four :register Storage class
Let's start with a non-human explanation :
register Storage classes are used to define storage in registers rather than RAM Local variable in . This means that the maximum size of the variable is equal to the size of the register ( It's usually a byte ), And you can't apply one yuan to it ’&' Operator ( Because it has no memory location )
Is not a face confused ? To understand the above , First of all, understand , What is a register ? What is? RAM? What is a dollar ’&' Operator ?
Let's see what is RAM?
Random-Access Memory Random access memory , It is the memory module of the computer . For storing dynamic data .( Also called running memory ) When the system is running , The operating system needs to be removed from the hard disk (ROM) Read it out , Put it in RAM Run in .
Let's see what registers are ?
Baidu Encyclopedia's explanation :
The register is CPU Small internal storage areas for storing data , It is used to temporarily store the data and results involved in the operation . In fact, register is a common sequential logic circuit , But this kind of sequential logic circuit only includes memory circuit . The memory circuit of the register is composed of a latch or a trigger , Because a latch or trigger can store 1 Bit binary number , So by the N A latch or trigger can form N Bit register . Registers are part of the CPU . Register is a high-speed storage unit with limited storage capacity , They can be used to hold instructions 、 Data and address .
Is it right to be confused ?
Then I saw the words of a big man on the Internet , It's easy to understand . Here's a quote :
Know what a register is ? Have you ever seen a eunuch ? No, ? Actually, I didn't . No, it doesn't matter , Once you see it, you'll be in big trouble ._, Everyone has seen ancient costume plays , When the emperors had to read the memorials , Ministers always give the memorial to the little eunuch next to the emperor first ,
The little eunuch will be handed over to the emperor . This little eunuch is just a transit station , There is no other function . Then let's think of our CPU.CPU Isn't it our Comrade Emperor ? The minister is equivalent to our memory (RAM), Take the data from him .
That little eunuch is our register ( Don't think about it here CPU The cache area of ). The data is taken out of memory and put into the register first , then CPU Then read data from the register to process , After processing, the data is also stored in memory through registers ,
CPU Do not deal directly with memory . The point here is : The little eunuch took the memorial from the minister on his own initiative , Then take the initiative to hand it over to the emperor , But registers are not so conscious , It never takes the initiative to do anything . An emperor may have many small eunuchs ,
So one CPU There can also be many registers , Different models CPU There are different numbers of registers .
Why is it so troublesome ? Speed ! Because of the speed . Registers are actually small pieces of storage space , But its access speed is much faster than memory . You can get the month first , It's away from CPU Very close ,CPU Reach out and get the data ,
It's much faster than looking for data at a certain address in such a large piece of memory ? Then someone asked, since it is so fast , Let's change our memory and hard disk into registers . Here's what I'm going to say : You are rich !
Finally, take a look at ’&' Operator
Simply put, it is to take the address character .
What is an address character ? seeing the name of a thing one thinks of its function , Is to get the memory address of the current variable , To get the address of that variable , Just use & Follow that variable .
vim quzhifu.c Write the following :
#include <stdio.h> // The header file
char a; // Defining variables
short b;
int c;
void main(){
// Program entrance
a = 1; // Assign a value to a variable
b = 2;
c = 3;
printf("%x %x %x \n", &a, &b, &c);
}
Kali Linux The operation results are as follows :
┌──(rootkali)-[~/Desktop/c_test]
└─# ./quzhifu
357ba034 357ba036 357ba038
Now go back to see register Storage class :
1、 Verified register Cannot apply to it '&' Operator :
vim register.c Write the following :
#include <stdio.h>
int main(){
register int a;
printf("%x \n", &a);
return 0;
}
Error will be reported at compile time , This proves ,register Cannot apply to it '&' Operator .
┌──(rootkali)-[~/Desktop/c_test]
└─# gcc register.c -o register
register.c: In function ‘main’:
register.c:5:5: error: address of register variable ‘a’ requested
5 | printf("%x \n ", &a);
| ^~~~~~
2、 Only local automatic variables and formal parameters can be used as register variables , Other ( Such as global variables 、 Structure 、 Share internal variables ) no way . Specially , Static local variables cannot be defined as register variables .
struct _STRUCT_NAME_
{
register int a; // error
};
union _UNION_NAME_
{
register int b; // error
};
register int c; // error
void main()
{
register static int d = 0; // error
}
5、 ... and :static Storage class
static Keywords can not only be used to modify variables , It can also be used to modify functions . In the use of static When a keyword modifies a variable , We call this variable a static variable .
Static variables are stored in the same way as global variables , It's all static storage . But what needs special explanation here is , Static variables belong to static storage mode , Variables that belong to static storage are not necessarily static variables .
for example , Although global variables belong to static storage , But it's not a static variable , Must be static It can become a static global variable only after it is defined .
The role of concealment and isolation :
The scope of the global variable is the entire source program , When a source program consists of multiple source files , Global variables are valid in each source file . If we want global variables to be used only in this source file , Cannot reference... In other source files , In other words, limiting its scope is only valid in the source file that defines the variable , However, it cannot be used in other source files of the same source program . At this time , You can add keywords before global variables static To achieve , Make the global variable be defined as a static global variable . This avoids errors in other source files . It also plays a role in hiding and isolating errors from other source files , Conducive to modular programming .
Maintain the persistence of variable contents :
occasionally , We hope that the value of the local variable in the function will not disappear after the function call , And still retain its original value . That is, the storage unit it occupies will not be released , The next time the function is called , The value of its local variable still exists , That is, the value at the end of the last function call . Now , We should use the local variable with the keyword static Declare as “ Static local variables ”. When declaring a local variable as a static local variable , This changes the storage location of local variables , That is, from the original stack to the static storage area . This makes it look like a global variable , In fact, the main difference between static local variables and global variables is visibility , Static local variables are visible only in the code block in which they are declared .
Verify with an example :
example :
┌──(rootkali)-[~/Desktop/c_test]
└─# vim static.c
#include <stdio.h>
void func(){
static int i = 1;
i += 1;
printf("%d \n", i);
}
int main(){
func();
func();
return 0;
}
┌──(rootkali)-[~/Desktop/c_test]
└─# gcc static.c -o static
┌──(rootkali)-[~/Desktop/c_test]
└─# ./static
2
3
Conclusion :
static int i = 1; The output 2 3
int i = 1; The output 2 2
So :static The occupied storage unit is not released , The next time the function is called , The value of its local variable still exists , That is, the value at the end of the last function call .
6、 ... and :extern Storage class
extern The storage class is used to provide a reference to a global variable , Global variables are visible to all program files . When you use ‘extern’ when , For variables that cannot be initialized , Will point the variable name to a previously defined storage location . When there are multiple files and a global variable or function is defined that can be used in other files , It can be used in other files extern To get a reference to a defined variable or function .extern Is used to declare a global variable or function in another file .
extern Modifiers are usually used when two or more files share the same global variable or function .
Example is given to illustrate :
In the same directory , Create two files .
First file :extern_main.c
#include <stdio.h>
int count;
extern void write_extern();
main(){
count = 5;
write_extern();
}
Second document :extern_support.c
#include <stdio.h>
extern int count;
void write_exteren(){
printf("count is %d \n", count);
}
ad locum , In the second file extern Keyword used to declare that already in the first file main.c As defined in count. Now? , Compile these two files , As shown below :
┌──(rootkali)-[~/Desktop/c_test]
└─# gcc extern_main.c extern_support.c -o extern
extern_main.c:5:1: warning: return type defaults to ‘int’ [-Wimplicit-int]
5 | main(){
| ^~~~
┌──(rootkali)-[~/Desktop/c_test]
└─# ./extern
count is 5
边栏推荐
- 012 C语言基础:C数组
- 系统架构设计——互联网金融的架构设计
- Nignx configuring single IP current limiting
- Installation of low code development platform nocobase
- 019 C语言基础:C预处理
- Office VR porn, coquettish operation! The father of Microsoft hololens resigns!
- 微服务系统设计——分布式事务服务设计
- 如何让 EF Core 6 支持 DateOnly 类型
- [BJDCTF2020]The mystery of ip
- MATLAB | 基于分块图布局的三纵坐标图绘制
猜你喜欢
![[数组]BM94 接雨水问题-较难](/img/2b/1934803060d65ea9139ec489a2c5f5.png)
[数组]BM94 接雨水问题-较难

ERP需求和销售管理 金蝶

Products change the world

Fplan powerplan instance

PostgreSQL basic command tutorial: create a new user admin to access PostgreSQL

微服务系统设计——服务注册与发现和配置设计

Cultural tourism night tour | stimulate tourists' enthusiasm with immersive visual experience

文旅夜游|以沉浸式视觉体验激发游客的热情

MATLAB | 三个趣的圆相关的数理性质可视化

手撸promise【二、Promise源码】【代码详细注释/测试案例完整】
随机推荐
日志收集系統
Nacos调用微服务两个问题:1.Load balancer does not contain an instance for the service 2.Connection refused
009 C语言基础:C循环
跟着BUU学习Crypto(周更)
Microservice system design - service fusing and degradation design
016 C语言基础:C语言枚举类型
012 C语言基础:C数组
PostgreSQL basic command tutorial: create a new user admin to access PostgreSQL
【Unity】UI交互组件之按钮Button&可选基类总结
缓存综合项目--秒杀架构
A^2=e | the solution of the equation | what exactly can this equation tell us
Kotlin Compose 自定义 CompositionLocalProvider CompositionLocal
Learn crypto from Buu (Zhou Geng)
010 C语言基础:C函数
Cultural tourism light show breaks the time and space constraints and shows the charm of night tour in the scenic spot
如何系统学习LabVIEW?
WPF open source control library extended WPF toolkit Introduction (Classic)
[BJDCTF2020]The mystery of ip
Argo Workflows —— Kubernetes的工作流引擎入门
真xx相来了?测试/开发程序员为什么不愿意加班,这是个疯狂的状态......