1491 views|0 replies

3836

Posts

19

Resources
The OP
 

The wonderful use of the C language keyword static [Copy link]

Why do we say static is wonderful? It is indeed wonderful. In the process of software development or single-chip microcomputer development, people always think that static is a static variable. If you add it in front of the variable type, it will be automatically cleared to 0. Also, if you add the static keyword, no matter it is a variable or a keyword, in a local variable, the variable is only visible locally. In the global area, static variables or functions are only visible in this file. Of course, there is an important feature that has been overlooked. . . . The value of a local variable modified by static is the value after the last function call ends. It is precisely because of this feature that we can use this feature of zh to complete many functions. Let’s briefly summarize the characteristics of static: The keyword static can modify functions and variables The content it modifies is static The local variables modified by static are static local variables Features: 1. The life cycle of the entire program 2. The access scope is the same as that of ordinary variables 3. The value of a local variable modified by static is the value after the last function call ends 4. static can also modify global variables or functions If a static local variable is not initialized when it is defined, the system will give it 0 as the default initial value 5. If multiple file operations are involved, the global variable modified by static can only be used in this file. When static modifies a function, it also means limiting the scope of use and can only be used in this file. 6. Ordinary local variables are allocated space on the stack, and the system is responsible for allocation and release and recovery. Global variables and static local variables actually allocate space in the static area. Let's write a program to verify it: (only verify the third function) #include [color=#000000 ]void fun(); int main()[/color ] { fun(); fun(); [size =4] return 0; } [color =#000000] void fun()[ /size] { static int a = 0; a++ ; [size=4 ] printf("a:%d\n",a); }[/color ] Execution result: [backcolor= From the execution results, we can see that the fun() function is called twice in the main function. The first time it is called, a is incremented, and the printed result is 1 [size =4] The second call to the fun() function , a is no longer 0, but 1, so when it is added to itself, a becomes 2.

This post is from Microcontroller MCU
 

Guess Your Favourite
Just looking around
Find a datasheet?

EEWorld Datasheet Technical Support

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京B2-20211791 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号
快速回复 返回顶部 Return list