About in-scope functions

Some time ago doing a project in c i ended up using a beautiful feature of gcc (i found out only later that it's not standard, but still supported by gcc for c language), of being able to write a function in a specific scope.

That function would not exist outside of the scope, and can access all variables of that scope, pretty much the way a normal function can access globals.

And in a couple cases this is really amazing.
Now i'm not asking if it's possible in c++, i know it's not.
The two workarounds only achieve the "not exist outside of the scope feature", but both lack the "access all varibles of that scope" one. (which are dummy class or local lambda assigned to a function type variable.)

What i'm asknig is:
1) Why aren't nested functions part of both C and C++ standard? Is there any specific reason, considered it's clearly possible since gcc already does that?
2) Why there isn't a C++ adaptation to the non-standard nested classes system used in C by gcc?
3) Why isn't the idea of adding nested functions to the standard being taken into account? (it isn't as far as i know at least, i might likely be wrong)
In what way does this not have access to all variables of the scope? What does this not do that you want to do?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <string>
#include <iostream>

using std::string;


int main()
{
  string beans("beans");

  auto func = [&](){std::cout << beans << '\n';};
  func();

  {
    // new scope
    string banana("banana");
    auto func2 = [&](){
                   beans += '!';
		   std::cout << beans << ' ' << banana << '\n';};
    func2();
  }

  // cannot call func2() here ; it does not exist outside of the scope


  func();
}

Last edited on
lol nevermind i forgot the & in [&] xD
Still my questions persist, this is a workaround...
this is a workaround...


How is it a workaround?

Does it not do everything needed? Does it cause additional problems?
That function would not exist outside of the scope, and can access all variables of that scope, pretty much the way a normal function can access globals.
It is called lambda and is standard since C++11:

https://en.cppreference.com/w/cpp/language/lambda

Topic archived. No new replies allowed.