C++入门经典-例4.10-使用static变量实现累加

1:静态变量static可以分为静态局部变量和静态全局变量,静态局部变量的值在函数调用结束后不消失,静态全局变量只能在本源文件中使用。

静态变量属于静态存储方式,它具有以下特点:

(1)静态变量在函数内定义,在程序退出时释放,在整个程序的运行期间都不释放,也就是说它的生存周期为整个源程序。

(2)静态变量的作用域与自动变量相同,在函数内定义就在函数内使用,尽管改变量还继续存在,但是不能使用它,如果再次调用定义它的函数时,便可继续使用它。

(3)编译器会为静态局部变量赋予0值。

代码如下:

// 4.10.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
using namespace std;
int add(int x)
{
    static int n=0;
    n=n+x;
    return n;
}
void main()
{
    int i,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

运行结果:

原文地址:https://www.cnblogs.com/lovemi93/p/7520612.html