Home Backend Development C++ Practical application scenarios and usage skills of the static keyword in C language

Practical application scenarios and usage skills of the static keyword in C language

Feb 21, 2024 pm 07:21 PM
static Application scenarios skills Scope c language programming

Practical application scenarios and usage skills of the static keyword in C language

Practical application scenarios and usage skills of static keyword in C language

1. Overview
static is a keyword in C language, used for modification variables and functions. Its function is to change its life cycle and visibility during program running, making variables and functions static. This article will introduce the practical application scenarios and usage techniques of the static keyword, and illustrate it through specific code examples.

2. Static variables

  1. Extension of the life cycle of variables
    Using the static keyword to modify local variables can extend their life cycle to the entire running process of the program. This means that the value of the variable remains unchanged even if it leaves the scope in which it resides. This feature is very useful in scenarios where the state of a variable needs to be maintained. For example, in a recursive function, we can use static variables to record the number of times the function is called.
#include <stdio.h>

int recursive()
{
    static int count = 0;
    count++;

    printf("当前递归次数:%d
", count);

    if (count < 5)
    {
        recursive();
    }

    return count;
}

int main()
{
    int result = recursive();

    printf("递归结束,共计调用次数:%d
", result);

    return 0;
}
Copy after login

Running results:

当前递归次数:1
当前递归次数:2
当前递归次数:3
当前递归次数:4
当前递归次数:5
递归结束,共计调用次数:5
Copy after login

It can be seen that by using the static keyword to modify the count variable, the value of the variable is maintained during the recursive call, achieving the accumulation of the number of recursions. .

  1. Control the visibility of variables
    Using the static keyword to modify a global variable can limit its scope to the current source file and avoid being accessed in other source files. In this way, we can define static variables with the same name in different source files without conflict problems. This feature is very useful in scenarios where you need to share variables while ensuring the closure of the variable scope.
// file1.c
#include <stdio.h>

static int global = 10;

void printGlobal()
{
    printf("file1.c中的global:%d
", global);
}
Copy after login
// file2.c
#include <stdio.h>

static int global = 20;

void printGlobal()
{
    printf("file2.c中的global:%d
", global);
}
Copy after login
// main.c
#include <stdio.h>

extern void printGlobal();

int main()
{
    printGlobal();

    return 0;
}
Copy after login

Run result:

file1.c中的global:10
Copy after login

In this example, because the global variable is modified by the static keyword, static variables with the same name can be defined in different source files without Cause conflict.

3. Static function

  1. Control the visibility of the function
    Using the static keyword to modify the function can limit its scope to the current source file and avoid using it in other source files. is called in. In this way, we can define static functions with the same name in different source files without conflict problems. This feature is very useful in scenarios where you need to encapsulate function implementation without exposing it to other modules.
// file1.c
#include <stdio.h>

static void privateFunc()
{
    printf("这是file1.c中的私有函数
");
}

void publicFunc()
{
    printf("这是file1.c中的公共函数
");
    privateFunc();
}
Copy after login
// file2.c
#include <stdio.h>

static void privateFunc()
{
    printf("这是file2.c中的私有函数
");
}

void publicFunc()
{
    printf("这是file2.c中的公共函数
");
    privateFunc();
}
Copy after login
// main.c
#include <stdio.h>

extern void publicFunc();

int main()
{
    publicFunc();

    return 0;
}
Copy after login

Running results:

这是file1.c中的公共函数
这是file1.c中的私有函数
Copy after login

In this example, since the privateFunc function is modified by the static keyword, static functions with the same name can be defined in different source files without Cause conflict.

  1. The function is only initialized once
    Using the static keyword to modify a local variable can cause the variable to be initialized only once and keep its value unchanged between multiple calls to the function. This feature is very useful in scenarios where the state of a certain variable needs to be recorded. For example, in a function you need to record the number of function calls.
#include <stdio.h>

void printCount()
{
    static int count = 0;
    count++;

    printf("函数调用次数:%d
", count);
}

int main()
{
    int i;
    for (i = 0; i < 5; i++)
    {
        printCount();
    }

    return 0;
}
Copy after login

Running results:

函数调用次数:1
函数调用次数:2
函数调用次数:3
函数调用次数:4
函数调用次数:5
Copy after login

You can see that by using the static keyword to modify the count variable, the value of the variable is maintained between multiple calls of the function, realizing the function The cumulative number of calls.

4. Summary
This article introduces the practical application scenarios and usage techniques of the static keyword in C language. By describing the examples of static variables and static functions in detail, we can find that the static keyword plays an important role in extending the life cycle of variables, controlling the visibility of variables and functions, and controlling the number of variable initializations. Reasonable application of the static keyword can improve the readability, maintainability and security of the program. I hope this article will be helpful to readers in their application of C language programming.

The above is the detailed content of Practical application scenarios and usage skills of the static keyword in C language. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Usage of typedef struct in c language Usage of typedef struct in c language May 09, 2024 am 10:15 AM

typedef struct is used in C language to create structure type aliases to simplify the use of structures. It aliases a new data type to an existing structure by specifying the structure alias. Benefits include enhanced readability, code reuse, and type checking. Note: The structure must be defined before using an alias. The alias must be unique in the program and only valid within the scope in which it is declared.

How to solve variable expected in java How to solve variable expected in java May 07, 2024 am 02:48 AM

Variable expected value exceptions in Java can be solved by: initializing variables; using default values; using null values; using checks and assignments; and knowing the scope of local variables.

Advantages and disadvantages of closures in js Advantages and disadvantages of closures in js May 10, 2024 am 04:39 AM

Advantages of JavaScript closures include maintaining variable scope, enabling modular code, deferred execution, and event handling; disadvantages include memory leaks, increased complexity, performance overhead, and scope chain effects.

What does include mean in c++ What does include mean in c++ May 09, 2024 am 01:45 AM

The #include preprocessor directive in C++ inserts the contents of an external source file into the current source file, copying its contents to the corresponding location in the current source file. Mainly used to include header files that contain declarations needed in the code, such as #include <iostream> to include standard input/output functions.

C++ smart pointers: a comprehensive analysis of their life cycle C++ smart pointers: a comprehensive analysis of their life cycle May 09, 2024 am 11:06 AM

Life cycle of C++ smart pointers: Creation: Smart pointers are created when memory is allocated. Ownership transfer: Transfer ownership through a move operation. Release: Memory is released when a smart pointer goes out of scope or is explicitly released. Object destruction: When the pointed object is destroyed, the smart pointer becomes an invalid pointer.

Can the definition and call of functions in C++ be nested? Can the definition and call of functions in C++ be nested? May 06, 2024 pm 06:36 PM

Can. C++ allows nested function definitions and calls. External functions can define built-in functions, and internal functions can be called directly within the scope. Nested functions enhance encapsulation, reusability, and scope control. However, internal functions cannot directly access local variables of external functions, and the return value type must be consistent with the external function declaration. Internal functions cannot be self-recursive.

What are the application scenarios of factory pattern in java framework? What are the application scenarios of factory pattern in java framework? Jun 01, 2024 pm 04:06 PM

The factory pattern is used to decouple the creation process of objects and encapsulate them in factory classes to decouple them from concrete classes. In the Java framework, the factory pattern is used to: Create complex objects (such as beans in Spring) Provide object isolation, enhance testability and maintainability Support extensions, increase support for new object types by adding new factory classes

The difference between let and var in vue The difference between let and var in vue May 08, 2024 pm 04:21 PM

In Vue, there is a difference in scope when declaring variables between let and var: Scope: var has global scope and let has block-level scope. Block-level scope: var does not create a block-level scope, let creates a block-level scope. Redeclaration: var allows redeclaration of variables in the same scope, let does not.

See all articles