Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we have functions inside functions in C++?

Tags:

c++

I mean something like:

int main()  {   void a()    {       // code   }   a();    return 0; } 
like image 755
Rella Avatar asked Dec 01 '10 13:12

Rella


People also ask

Can you put a function inside a function?

If you define a function inside another function, then you're creating an inner function, also known as a nested function. In Python, inner functions have direct access to the variables and names that you define in the enclosing function.

Is function inside a function bad?

no, there's nothing wrong with that at all, and in js, it's usually a good thing. the inside functions may not be a pure function, if they rely on closure variables. If you don't need a closure or don't need to worry about polluting your namespace, write it as a sibling.


1 Answers

Modern C++ - Yes with lambdas!

In current versions of c++ (C++11, C++14, and C++17), you can have functions inside functions in the form of a lambda:

int main() {     // This declares a lambda, which can be called just like a function     auto print_message = [](std::string message)      {          std::cout << message << "\n";      };      // Prints "Hello!" 10 times     for(int i = 0; i < 10; i++) {         print_message("Hello!");      } } 

Lambdas can also modify local variables through **capture-by-reference*. With capture-by-reference, the lambda has access to all local variables declared in the lambda's scope. It can modify and change them normally.

int main() {     int i = 0;     // Captures i by reference; increments it by one     auto addOne = [&] () {         i++;      };      while(i < 10) {         addOne(); //Add 1 to i         std::cout << i << "\n";     } } 

C++98 and C++03 - Not directly, but yes with static functions inside local classes

C++ doesn't support that directly.

That said, you can have local classes, and they can have functions (non-static or static), so you can get this to some extend, albeit it's a bit of a kludge:

int main() // it's int, dammit! {   struct X { // struct's as good as class     static void a()     {     }   };    X::a();    return 0; } 

However, I'd question the praxis. Everyone knows (well, now that you do, anyway :)) C++ doesn't support local functions, so they are used to not having them. They are not used, however, to that kludge. I would spend quite a while on this code to make sure it's really only there to allow local functions. Not good.

like image 94
sbi Avatar answered Sep 20 '22 13:09

sbi