Search code examples
c++language-designlocal-functions

Why are local function definitions illegal in C++?


It comes across as odd to me that local function definitions are illegal. As things stand now, I doubt it would be too hard to implement, and the erasure of what could be a potential feature (like in python for example) for no reason at all seems strange, especially for a language like C++, where you can shoot yourself in the foot if you want to. The illegality of local function definitions seems doubly so strange if things like this are allowed.

int main()
{
    void func(); // Allowed?

    class BypassRules {
    public:
        static void func() { return; }
    };

    BypassRules::func();
    func();

    return 0;
}

void func() { return; }

Oddly enough, local function 'Declarations' are allowed, but definitions are not. And the rule on local function definitions not being allowed can be easily bypassed by writing a class encapsulator. So, could I have some clarification? Why are local class definitions classified as 'illegal' in C++?


Solution

  • Oddly enough, local function 'Declarations' are allowed, but definitions are not. And the rule on local function definitions not being allowed can be easily bypassed by writing a class encapsulator. So, could I have some clarification? Why are local class definitions classified as 'illegal' in C++?

    Illegal because they don't make much sense, whether it may be defining a function inside a function or a class inside a function like main().

    But then you can always use workarounds, such as:

    • For functions you can always use a lambda, which acts as an anonymous temporary function, can be called inside main plus be used within function parameters as well.

    It can be invoked whenever necessary and subsequently discarded like a throw-away function, but it does the job - whatever you would expect from a function.

    Example:

    int main() 
    { 
      // Define within the scope of main()
      auto temp = [](int x)
      { std::cout<< x; 
      }
      temp(10); // call like a function
    }
    

    • For classes, use static functions, (being local to the translation unit) with public access specifiers (as you did in your question).

    Example:

    int main()
    {
       class temp
       {  public:
          static void a()
          {  std::cout<< 10;
          }
       };
       temp::a();
    }
    

    Output for both cases: 10

    Provided there are alternatives approaches like the ones above to define a function/class/struct inside main(), there isn't really much of a point to make them legal. ¯\_(ツ)_/¯