C++ 靜態局部變量的作用


#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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM