C-The role of the static keyword

Share a big cow's artificial intelligence tutorial. Zero-based! Easy to understand! Funny and humorous! Hope you join the artificial intelligence team too! Please click http://www.captainbed.net

In the C language, the static keyword is used to define global static variables, local static variables and static functions.

Define global static variables

Add the keyword static in front of a global variable, and the global variable becomes a global static variable. Global static variables have the following characteristics:

  • The variable allocates memory in the global data area
  • If not initialized, its default value is 0
  • The variable is visible in this file from the beginning of the definition to the end of the file

Define local static variables

Add the keyword static in front of a local variable, and the local variable becomes a local static variable. Local static variables have the following characteristics:

  • The variable allocates memory in the global data area
  • The variable always resides in the global data area until the end of the program
  • Its scope is a local scope. When the function or statement block that defines it ends, its scope ends.

Define static function

Add the static keyword before the function return type, and the function is defined as a static function. Static functions have the following characteristics:

  • Static functions can only be used in this source file
  • The inline function declared in the file scope defaults to the static type

Summary: The difference between global and local static variables defined by static is that the scope and visible domain of global static variables start from the definition of the file to the end of the entire file; while the visible domain of local static variables starts from the definition of the file To the end of the entire file, the scope is from the definition of the statement block to the end of the statement block. The best example of using static local variables is to implement the function of counting the number of times​​​​​​​.

Guess you like

Origin blog.csdn.net/chimomo/article/details/114255697