循环内的函数声明

Function declaration inside loop

本文关键字:声明 函数 循环      更新时间:2023-10-16

我想知道当我们在循环中声明一个运行x次的函数时会发生什么。例如

int main() {
for(int i=0;i<100;i++)
{
void my_func(){
cout<<"Hello! Brother"<<endl;
}
}
}

您尝试执行的操作无法使用正常功能。 但是,您可以使用 lambda 来实现所需的结果:

int main()
{
for (int i = 0; i < 100; i++)
{
// Create local lambda and call it afterwards.
auto myfunc = []() {
cout << "Hello! Brother" << endl;
};
myfunc();
// alternatively, call lambda in situ
// []() { cout << "Hello! Brother" << endl; }();
}
}