当前位置:网站首页>Easy to understand C language keyword static

Easy to understand C language keyword static

2022-06-26 01:49:00 So it is^^

One :static Modify local variables

Unused static modification

use static After modification

  From the code and results in Figure 1, we can see that Not by static modification The first 79 Line code , local variable i In the exit test Function time Will destroy data , Because the first 86 Row to 90 Code loop 10 Secondary entry test() function , Run out test Function is a local variable i Data destruction for , So the result is 10 Time i The value of is 2

As can be seen from Figure 2 , Every time you call test function , The use of i It's all left over from the last function call i, hold The data of local variables is saved , So the results i The value of is 2~11

You can see it here static Modified local variables It will not be destroyed even if it is out of its own scope , Equivalent to changing the life cycle of this local variable

Two :static Modify global variable

LNK In fact, it refers to link error

Figure 1 shows Global variables can be used in other files of the whole project , This is because global variables have external link attributes. As you can see in Figure 2 after static After modification , Global variables can only be used in source files , Other documents cannot be used , It gives us the feeling that the scope has become smaller

We can regard the whole project as a building , Different documents in a project are equivalent to different floors , The global variable is equivalent to a person on a certain floor of that building , In the absence of static When decorating, he can be in that building ( engineering ) Through the stairs ( link ) Can work in different floors ( file ), But once it's been static After modification , It is equivalent to dismantling the stairs ( Does not have external attributes ) A man can only be on his floor ( file ) Work in China

3、 ... and :static Modify function

whole static Decorating functions is similar to decorating global variables , It also makes the original function that can be called in other files of the whole project only in its source file ( That is, where the function is located .c perhaps .h file )

原网站

版权声明
本文为[So it is^^]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206260012409949.html