1: Static variable statics can be divided into static local variables and static global variables, the values of static local variables do not disappear after the function call, static global variables can only be used in the source file.
Static variables are static storage, which has the following characteristics:
(1) A static variable is defined within a function, released when the program exits, and is not released during the entire program's operation, that is, its lifetime is the entire source program.
(2) The scope of a static variable is the same as the automatic variable, and the definition within the function is used within the function, although the amount of change continues to exist, but it cannot be used, and it can continue to be used if the function that defines it is called again.
(3) The compiler assigns a 0 value to a static local variable.
The code is as follows:
//4.10.cpp: Defines the entry point of the console application. //#include"stdafx.h"#include<iostream>using namespacestd;intAddintx) { Static intn=0; N=n+x; returnN;}voidMain () {inti,j,sum; cout<<"input the number:"<<Endl; CIN>>i; cout<<"The result is:"<<Endl; for(j=1; j<=i;j++) {sum=Add (j); cout<< J <<":"<<sum <<Endl; }}View Code
Operation Result:
Getting Started with C + + Classic-Example 4.10-using static variables to achieve accumulation