第十二周项目1-阅读程序(一)

含有有静态局部变量

/*
 *Copyright (c) 2014,烟台大学计算机学院
 *All gight reserved.
 *文件名称:temp.cpp
 *作者:邵帅
 *完成时间:2014年11月12日
 *版本号:v1.0
*/
#include <iostream>
using namespace std;
int f(int n);
int main()
{
    cout<<f(5)<<"  ";
    cout<<f(8)<<endl;
    return 0;
}
int f(int n)
{
    static int a=2;
    int b=0;
    a+=n;
    b+=a;
    return b;
}

运行结果:



/*
 *Copyright (c) 2014,烟台大学计算机学院
 *All gight reserved.
 *文件名称:temp.cpp
 *作者:邵帅
 *完成时间:2014年11月12日
 *版本号:v1.0
*/
#include <iostream>
using namespace std;
int func (int a,  int b)
{
    static int m=0, i=2;
    i+=m+1;
    m=i+a+b;
    return m;
}
int main()
{
    int k=4, m=1, p;
    p=func(k, m);
    cout<<p<<endl;
    p=func(k, m);
    cout<<p<<endl;
    return 0;
}

运行结果:



知识点:有时候希望函数中的局部变量的值在函数调用结束后不消失而保留原值,即其占用的的储存单元不释放,在下一次该函数调用时,该变量保留上一次函数调用结束时的值。这时的局部变量为静态局部变量(static)

posted @ 2014-11-12 22:06  麻麻麻麻鱼鱼  阅读(123)  评论(0编辑  收藏  举报