-4

I have search through google/stack overflow etc. but I could not find the proper/exact solution for this. I know latest C++ revision supports Lambda function by which we can achieve, and also I know we should avoid defining a function inside another function. But I'm curious why can not we have function definition inside function according to C++ standard?.

like following:

int print() {
   void test(){
     // statements
   }
}

I know people will mark this as duplicate but in those questions no one has given satisfactory answer, to make this to be highlight I have asked here.

learn2code
  • 153
  • 2
  • 8

2 Answers2

0

I remembered now that you could emulate it in the pre c++11 days like this:

void foo() {
  struct detail {
    static void bar() {
      //statements
    }
  };

  detail::bar();
}

Can even pass that as a callback from within foo. You should note however that there is no closure here. You can't access variables of foo in bar.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • We can achieve it by your solution which you've provided. But my question why we cannot define a function inside another? Is there any particular reason Does it effects the efficiency or performance? – learn2code Oct 20 '16 at 10:20
  • 1
    @Suchendra, without any closure mechanic it doesn't affect any metric of the program, other than code clarity. – StoryTeller - Unslander Monica Oct 20 '16 at 10:24
-2

Pretty sure you can:

int main() {
    auto curry = [] (auto f) {
        return [=] (auto x) {
            return [=] (auto y) {
                return f(x, y);
            };
        };
    };
}
Michael Foukarakis
  • 39,737
  • 6
  • 87
  • 123