#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