Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulating nested functions in C++

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.

like image 450
Paul McCutcheon Avatar asked Mar 18 '11 18:03

Paul McCutcheon


People also ask

What is nested function in C with example?

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.

Does C support nested functions?

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.

What is an example of 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.

Can I call a function inside another function in C?

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.


2 Answers

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); } 
like image 150
Ben Voigt Avatar answered Sep 21 '22 15:09

Ben Voigt


Turn your function into a functor as Herb Sutter suggests in this article

like image 23
Prasoon Saurav Avatar answered Sep 20 '22 15:09

Prasoon Saurav