您的位置:首页 > 其它

static静态局部变量的用法,最直接的解释,一看秒懂!

2016-02-22 19:55 309 查看
10行经典代码,两种结果,阐述static的作用。废话少说,直接码字。【看懂了,点个赞哈】

// 包含static静态局部变量i的结果,静态局部变量i都保存了前次test函数被调用后留下来的值。

#include <iostream>

using namespace std;

void test() {

static int i = 10;

cout << i<<endl;

i++;

}

void main() {

test();

test();

test();

system("pause");

}

运行结果: 10 11 12

// 不包含static静态局部变量的结果

#include <iostream>

using namespace std;

void test() {

int i = 10;

cout << i<<endl;

i++;

}

void main() {

test();

test();

test();

system("pause");

}

运行结果: 10 10 10

【举个例子:用static,编写3的立方小程序】
#include<iostream>

using namespace std;

int mul(int x)

{

static int n = 1;

n = n*x;

return n;

}

void main()

{

int i = 3;

int iResult;

for (int j = 1; j<4; j++)

{

iResult = mul(i);

}

cout << "Result :" << iResult << endl;

system("pause");

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: