Skip to main content

Nested function

Short answer

Standard C does not allow function definitions inside other functions. Nesting means calling one function from within another; the called function executes and returns a value to the caller.

What do you mean by nested function? Give an example.

A nested function means a function used inside another function. In standard C, a function cannot be defined inside another function; all functions are defined separately at the same level. Nesting is done by calling one function from within another function, forming a chain of function calls (nested calls). (Some compilers such as gcc allow defining a function inside another as a non-standard extension.)

#include <stdio.h>
int square(int n) { return n * n; }
int sum_of_squares(int a, int b)
{
    return square(a) + square(b);   /* function called inside another function */
}
int main(void)
{
    printf("%d\n", sum_of_squares(3, 4));
    return 0;
}

Output:

25

main() calls sum_of_squares(), which in turn calls square() twice. The result is 3² + 4² = 25.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 6 questions →