Quote:
Originally Posted by Kenny_Strawn
Is it possible to define functions within other functions in C++? I know it is the case in other languages.
|
I'm not certain, but I think you need to wrap it in struct or class to get behavior similar to a nested function:
Code:
#include <cstdio>
int y=1;
int main(int argc, char**argv)
{
int x=2;
struct
{
void operator()(int c)
{
printf("%d\n", y+c);
}
} print;
print(10);
return 0;
}
The red part defines a nested functor named print. A functor serves the purpose of a function without exactly being a function.
But, depending on which other language you mean, you may be surprised and disappointed with the behavior. Local variables in the outer function are not available to the inner.
If you change the y in two places in that code to be x. You might expect it to print 12 instead of 11. Or you might expect it to print 11. Instead it gives a compile error because the x in main hides the global x without being available itself, so there is no x in scope in the nested functor.