#015 – C++ does not support nested functions

Consider the following:

#include <iostream>

int main()
{
	int x = 10;
		
    void x_squared(int x) // Illegal: Nested function detected
    {
	   std::cout << x * x << "\\n";
    }

    x_squared(); // function call 
}

According to the rules of C++, nested functions are illegal. Functions must be implemented in the global namespace. Then they can be called in other functions.

Why is this the case?

This behaviour was inherited from C.

The justification was to simplify compilers, abide to memory limitations (back when computers were slow) and speed up runtime organization.

The alternative

C++ does have alternatives such as std::function, lambdas and std::bind which perform the same purpose.

Let’s refactor the example at the beginning of the page to use a lambda expression. We use a capture clause to capture x, which is defined in the function scope. Thus, allows the lambda to use it.

void foo() {
    int x = 10;

    auto x_squared = [x]() {
        std::cout << x * x << "\\n";
    };

    x_squared();
}

Leave a Reply

Your email address will not be published. Required fields are marked *