In C the following code works in gcc.
int foo( int foo_var ) { /*code*/ int bar( int bar_var ) { /*code*/ return bar_var; } return bar(foo_var); }
How can I achieve the same functionality of nested functions in C++ with the gcc compiler? Don't mind if this seems like a beginner question. I am new to this site.
A nested function is a function defined inside the definition of another function. It can be defined wherever a variable declaration is permitted, which allows nested functions within nested functions. Within the containing function, the nested function can be declared prior to being defined by using the auto keyword.
Nested function is not supported by C because we cannot define a function within another function in C. We can declare a function inside a function, but it's not a nested function.
Users typically create nested functions as part of a conditional formula. For example, IF(AVERAGE(B2:B10)>100,SUM(C2:G10),0). The AVERAGE and SUM functions are nested within the IF function.
No you can't have a nested function in C . The closest you can come is to declare a function inside the definition of another function. The definition of that function has to appear outside of any other function body, though.
Local functions are not allowed in C++, but local classes are and function are allowed in local classes. So:
int foo( int foo_var ) { /*code*/ struct local { static int bar( int bar_var ) { /*code*/ return bar_var; } }; return local::bar(foo_var); }
In C++0x, you would also have the option of creating a functor using lambda syntax. That's a little more complicated in C++03, but still not bad if you don't need to capture variables:
int foo( int foo_var ) { /*code*/ struct bar_functor { int operator()( int bar_var ) { /*code*/ return bar_var; } } bar; return bar(foo_var); }
Turn your function into a functor as Herb Sutter suggests in this article
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With