I mean something like:
int main() { void a() { // code } a(); return 0; }
If you define a function inside another function, then you're creating an inner function, also known as a nested function. In Python, inner functions have direct access to the variables and names that you define in the enclosing function.
no, there's nothing wrong with that at all, and in js, it's usually a good thing. the inside functions may not be a pure function, if they rely on closure variables. If you don't need a closure or don't need to worry about polluting your namespace, write it as a sibling.
In current versions of c++ (C++11, C++14, and C++17), you can have functions inside functions in the form of a lambda:
int main() { // This declares a lambda, which can be called just like a function auto print_message = [](std::string message) { std::cout << message << "\n"; }; // Prints "Hello!" 10 times for(int i = 0; i < 10; i++) { print_message("Hello!"); } }
Lambdas can also modify local variables through **capture-by-reference*. With capture-by-reference, the lambda has access to all local variables declared in the lambda's scope. It can modify and change them normally.
int main() { int i = 0; // Captures i by reference; increments it by one auto addOne = [&] () { i++; }; while(i < 10) { addOne(); //Add 1 to i std::cout << i << "\n"; } }
C++ doesn't support that directly.
That said, you can have local classes, and they can have functions (non-static
or static
), so you can get this to some extend, albeit it's a bit of a kludge:
int main() // it's int, dammit! { struct X { // struct's as good as class static void a() { } }; X::a(); return 0; }
However, I'd question the praxis. Everyone knows (well, now that you do, anyway :)
) C++ doesn't support local functions, so they are used to not having them. They are not used, however, to that kludge. I would spend quite a while on this code to make sure it's really only there to allow local functions. Not good.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With