C++ knowledge point 3: Use of static local variables static

The variables of a function are only defined when the function is used for the first time and are not defined on subsequent calls. Then the value will change each time it is called. What kind of variables should be used?

If you want to initialize a function when it is first called, then retain its state each time the function is called and allow its value to change between calls, you can use static local variables. Static local variables are initialized on the first function call and then retain their value on subsequent function calls.


Here is a C++ example that demonstrates how to use static local variables to achieve this behavior:

#include <iostream>

int my_function() {
	static int my_variable = 0; // 使用static关键字定义静态局部变量,在首次调用时初始化
	my_variable += 1;           // 在每次函数调用时改变值
	return my_variable;
}

int main() {
	std::cout << my_function() << std::endl; // 输出 1(首次调用初始化)
	std::cout << my_function() << std::endl; // 输出 2(每次调用值发生变化)
	return 0;
}

Guess you like

Origin blog.csdn.net/pingchangxin_6/article/details/132685027