In C language, the static keyword is used to modify a variable, function or class member to have a static scope and have the following characteristics: Internal linkage: It can only be accessed or called in the file in which it is declared. Retain values: Variables and local function variables retain their values until the end of the program. Class scope: Class members belong to the entire class, and all instances share the same data. Constants: static const class members can be declared as compile-time constants.
Usage of static
in C language
What is static
?
static
is a keyword used to modify variables, functions or class members to indicate that they have static scope.
static
Scope of variables
For variables, static
means:
static
A variable can only be accessed within the file in which it is declared. static
A variable retains its value until the end of the program, even if the function it is in has exited. static
variables are initialized to 0, and local static
variables are initialized to garbage values. The static
scope of a function
For a function, static
means:
static
A function can only be called within the file in which it is declared. static
Local variables of a function have the same internal scope and value retention properties as static
variables. static
scope of class members
For class members, static
means:
static
Class members belong to the entire class, not to any specific object. static
class members. static const
Class members can be declared as compile-time constants. When to use static
?
Common scenarios for using static
include:
Example
<code class="c">// 外部变量,全局可见 int external_var = 10; // 静态变量,仅在本文件中可见且保留其值 static int static_var = 20; // 静态函数,仅在本文件中可见且局部变量保留其值 static void static_func() { static int local_var = 30; local_var++; } // 静态类成员,所有对象共享 class MyClass { public: static int shared_var = 40; };</code>
The above is the detailed content of How to use static in c language. For more information, please follow other related articles on the PHP Chinese website!