C 语言中的嵌套函数
在某些应用程序中,我们看到一些函数声明在另一个函数内部。这有时称为嵌套函数,但实际上这不是嵌套函数。这称为词法作用域。词法作用域在 C 中无效,因为编译器无法访问内部函数的正确内存位置。
嵌套函数定义不能访问周围块的局部变量。它们只能访问全局变量。在 C 中有两个嵌套范围:局部范围和全局范围。所以嵌套函数有一些有限的用法。如果我们想创建如下形式的嵌套函数,将会生成错误。
示例
#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();
}输出
text.c:(.text+0x1a): undefined reference to `my_fun2'
但是,GNU C 编译器的扩展允许声明嵌套函数。为此,我们必须在声明嵌套函数之前添加 auto 关键字。
示例
#include <stdio.h>
main(void) {
auto int my_fun();
my_fun();
printf("Main Function
");
int my_fun() {
printf("my_fun function
");
}
printf("Done");
}输出
my_fun function Main Function Done
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP