Can we have functions inside functions in C++?

后端 未结 12 2161
抹茶落季
抹茶落季 2020-11-22 14:51

I mean something like:

int main() 
{
  void a() 
  {
      // code
  }
  a();

  return 0;
}
12条回答
  •  名媛妹妹
    2020-11-22 15:46

    As others have mentioned, you can use nested functions by using the gnu language extensions in gcc. If you (or your project) sticks to the gcc toolchain, your code will be mostly portable across the different architectures targeted by the gcc compiler.

    However, if there is a possible requirement that you might need to compile code with a different toolchain, then I'd stay away from such extensions.


    I'd also tread with care when using nested functions. They are a beautiful solution for managing the structure of complex, yet cohesive blocks of code (the pieces of which are not meant for external/general use.) They are also very helpful in controlling namespace pollution (a very real concern with naturally complex/long classes in verbose languages.)

    But like anything, they can be open to abuse.

    It is sad that C/C++ does not support such features as an standard. Most pascal variants and Ada do (almost all Algol-based languages do). Same with JavaScript. Same with modern languages like Scala. Same with venerable languages like Erlang, Lisp or Python.

    And just as with C/C++, unfortunately, Java (with which I earn most of my living) does not.

    I mention Java here because I see several posters suggesting usage of classes and class' methods as alternatives to nested functions. And that's also the typical workaround in Java.

    Short answer: No.

    Doing so tend to introduce artificial, needless complexity on a class hierarchy. With all things being equal, the ideal is to have a class hierarchy (and its encompassing namespaces and scopes) representing an actual domain as simple as possible.

    Nested functions help deal with "private", within-function complexity. Lacking those facilities, one should try to avoid propagating that "private" complexity out and into one's class model.

    In software (and in any engineering discipline), modeling is a matter of trade-offs. Thus, in real life, there will be justified exceptions to those rules (or rather guidelines). Proceed with care, though.

提交回复
热议问题