1

This question may sound silly. But I am trying to create a function inside a function. But I am getting:

error : a function-definition is not allowed here before ‘{’ token 

Can someone please explain me ? how to solve this.

#include <iostream>

using namespace std;

class abc{
public:
    int func1(int key){
        int i=0;
        void func2(){
            i++;
            i++;
            cout<<i;
        }
     func2();
        return 0;
    }
};
int main()
{
 
    abc *obj= new abc();
    obj->func1(5);
    return 0;
}

and then I want to implement recursion in func1, like:

int func1(int key){
 int func2(){
        //code
      }
    //code
    func1(func2);
} 

Can I do this in C++?

Gabriel Staples
  • 36,492
  • 15
  • 194
  • 265
abcd
  • 21
  • 3
  • C++ doesn't allow such nested functions. Although, since C++11, you have [lambda expressions](https://stackoverflow.com/q/7627098/10871073). – Adrian Mole Dec 03 '20 at 18:53
  • i don't quite understand the "and then" you do not need to define one function inside the other to call them in a recursive fashion – 463035818_is_not_an_ai Dec 03 '20 at 19:16
  • Note: C **does** allow this, however. I defined a function inside `main()` in C, and it worked fine. I tried compiling the code in C++, and it failed with the same error as the OP. I turns out this is a C++ limitation, but NOT a C limitation. – Gabriel Staples Jun 04 '21 at 00:05

0 Answers0