Nested function in C
Nested functions are not a part of ANSI C, however, they are part of Gnu 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:
- 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.
- 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.
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)
{
}