C++ function within a function

Jimmy (xiaoke) Shen
1 min readAug 15, 2020

--

Function inside a function in Python

It is pretty easy for python to define a function within a function. Such as

def print_hello_world():
def print_I_love_world():
print("I love world")
print_I_love_world()
print_I_love_world()

What about C++?

#include<iostream>
using namespace std;
int main()
{

void print_I_love_world()
{
cout<<"I love world"<<endl;
return;
}
print_I_love_world();
cout<<"Hello world"<<endl;
return 0;
}

You will get some errors

function_in_function.cpp:6:5: error: function definition is not allowed here{^function_in_function.cpp:10:5: error: use of undeclared identifier 'print_I_love_world'print_I_love_world();^2 errors generated.

How to make it work?

#include<iostream>
using namespace std;
int main()
{

/*void print_I_love_world()
{
cout<<"I love world"<<endl;
return;
}
*/
function<void(void)> print_I_love_world = []()
{
cout<<"I love world"<<endl;
return;
};
print_I_love_world();
cout<<"Hello world"<<endl;
return 0;
}

A real problem

See this post: the first solution to the second problem if you wanna check a sample code.

More advanced practice can be found HERE.

Thanks for reading.

--

--

No responses yet