#include<iostream>
using namespace std;
void printhaha(){
static char haha[] = "haha";
cout<<"hello "<<haha<<endl;
haha[0] = haha[0]+1;
}
void printhehe(){
//cout<<"hello: "<<haha<<endl;//error: 'haha' was not declared in this scope
}
int main(){
printhaha();
printhaha();
printhaha();
return 0;
}
Java中静态局部变量是非法的,但是在C++中却是合法的。它同时拥有静态变量和局部变量的特性,即
编译时会自动初始化
会被放到内存的静态区
只能在局部被访问
在本例中,多次调用printhaha
函数,用的都是前一次退出时的结果,而且printhehe
函数无法访问haha
变量。
程序输出如下:
hello haha
hello iaha
hello jaha