
在一些应用程序中,我们发现有些函数是在另一个函数内部声明的。这有时被称为嵌套函数,但实际上这不是嵌套函数。这被称为词法作用域。在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</p><p>");
int my_fun() {
printf("my_fun function</p><p>");
}
printf("Done");
}my_fun function Main Function Done
以上就是在C语言中,嵌套函数的详细内容,更多请关注php中文网其它相关文章!
C语言怎么学习?C语言怎么入门?C语言在哪学?C语言怎么学才快?不用担心,这里为大家提供了C语言速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号