Home >Backend Development >C#.Net Tutorial >How to use static in c language

How to use static in c language

下次还敢
下次还敢Original
2024-05-09 10:48:21602browse

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.

How to use static in c language

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.

staticScope of variables

For variables, static means:

  • Internal linking: staticA variable can only be accessed within the file in which it is declared.
  • Retained value: staticA variable retains its value until the end of the program, even if the function it is in has exited.
  • Default initialization: Global 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:

  • Internal linkage: staticA function can only be called within the file in which it is declared.
  • Local scope: staticLocal variables of a function have the same internal scope and value retention properties as static variables.

staticscope of class members

For class members, static means:

  • Class scope: staticClass members belong to the entire class, not to any specific object.
  • Shared data: All class instances share the same static class members.
  • Constant: static constClass members can be declared as compile-time constants.

When to use static?

Common scenarios for using static include:

  • Restrict the visibility of variables or functions
  • Preserve the state of function local variables
  • Using shared data in a class
  • Declaring compile-time constants

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn