編程時有時需要將一段代碼中的某一塊只執行一次:
#include<iostream>
using namespace std;
int fun1(int a)
{
static bool once = true;//靜態變量初始化一次
if (once){
cout << "once" << endl; //只執行一遍的代碼
}
once = false;
cout << pow(a, 3) << endl;
return 0;
}
int main()
{
while (1)
{
fun1(3);
}
}