
- C Programming Tutorial
- C - Home
- C - Overview
- C - Environment Setup
- C - Program Structure
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Constants
- C - Storage Classes
- C - Operators
- C - Decision Making
- C - Loops
- C - Functions
- C - Scope Rules
- C - Arrays
- C - Pointers
- C - Strings
- C - Structures
- C - Unions
- C - Bit Fields
- C - Typedef
- C - Input & Output
- C - File I/O
- C - Preprocessors
- C - Header Files
- C - Type Casting
- C - Error Handling
- C - Recursion
- C - Variable Arguments
- C - Memory Management
- C - Command Line Arguments
- C Programming useful Resources
- C - Questions & Answers
- C - Quick Guide
- C - Useful Resources
- C - Discussion
Nested functions in C
In some applications, we have seen that some functions are declared inside another function. This is sometimes known as nested function, but actually this is not the nested function. This is called the lexical scoping. Lexical scoping is not valid in C because the compiler is unable to reach correct memory location of inner function.
Nested function definitions cannot access local variables of surrounding blocks. They can access only global variables. In C there are two nested scopes the local and the global. So nested function has some limited use. If we want to create nested function like below, it will generate error.
Example
#include <stdio.h> main(void) { printf("Main Function"); int my_fun() { printf("my_fun function"); // defining another function inside the first function. int my_fun2() { printf("my_fun2 is inner function"); } } my_fun2(); }
Output
text.c:(.text+0x1a): undefined reference to `my_fun2'
But an extension of GNU C compiler allows declaration of the nested function. For this we have to add auto keyword before the declaration of nested function.
Example
#include <stdio.h> main(void) { auto int my_fun(); my_fun(); printf("Main Function
"); int my_fun() { printf("my_fun function
"); } printf("Done"); }
Output
my_fun function Main Function Done
- Related Articles
- What are JavaScript Nested Functions?
- How to define nested functions in JavaScript?
- How do nested functions work in Python?
- What is the difference between closure and nested functions in JavaScript?
- Nested Classes in C#
- Nested Classes in C++
- Nested Tuples in C#
- How to append new information and rethrowing errors in nested functions in JavaScript?
- C# Nested Classes
- Thread functions in C/C++
- Functions in C/C++(3.5)
- What are nested classes in C#?
- What are nested namespaces in C#?
- Can namespaces be nested in C++?
- Iterator Functions in C#
