The use of static storage class in C++

  A static storage class instructs the compiler to keep a local variable alive for the lifetime of the program without creating and destroying it every time it enters and leaves the scope. Therefore, decorating a local variable with static preserves the value of the local variable between function calls.

  The static modifier can also be applied to global variables. When static modifies a global variable, it limits the scope of the variable to its file.

#include<iostream>

void func(void);

static int count = 10;

intmain()
{
	while(count--)
	{
		func();
	}
	return 0;
}

void func()
{
	static int i = 5;
	i++;
	std::cout << "i的值为:" << i << " count的值为:" << count << std::endl;
}

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325249590&siteId=291194637