Nested function in C

You cannot define a function within another function in standard C.

You can declare a function inside of a function, but it's not a nested function.

gcc has a language extension that allows nested functions. They are nonstandard, and as such are entirely compiler-dependent.


No, they don't exist in C.

They are used in languages like Pascal for (at least) two reasons:

  1. They allow functional decomposition without polluting namespaces. You can define a single publicly visible function that implements some complex logic by relying one or more nested functions to break the problem into smaller, logical pieces.
  2. They simplify parameter passing in some cases. A nested function has access to all the parameters and some or all of the variables in the scope of the outer function, so the outer function doesn't have to explicitly pass a pile of local state into the nested function.

Nested functions are not a part of ANSI C, however, they are part of Gnu C.


No you can't have a nested function in C. The closest you can come is to declare a function inside the definition of another function. The definition of that function has to appear outside of any other function body, though.

E.g.

void f(void)
{
    // Declare a function called g
    void g(void);

    // Call g
    g();
}

// Definition of g
void g(void)
{
}

I mention this as many people coding in C are now using C++ compilers (such as Visual C++ and Keil uVision) to do it, so you may be able to make use of this...

Although not yet permitted in C, if you're using C++, you can achieve the same effect with the lambda functions introduced in C++11:

void f()
{
    auto g = [] () { /* Some functionality */ }

    g();
}