【发布时间】:2011-05-16 16:31:47
【问题描述】:
我在某处读到 C 中允许嵌套函数(至少 GNU 编译器允许这样做)。考虑以下代码:
/* nestedfunc.c */
#include <stdlib.h> /* for atoi(3) */
#include <stdio.h>
int F (int q)
{
int G (int r)
{
return (q + r);
}
return (G (5));
}
int main (int argc, const char* argv[])
{
int q = 0;
if (argc > 1)
{
q = atoi (argv[1]);
}
printf ("%d\n", F (q));
return 0;
}
编译运行:
gcc -o nestedfunc -O2 -s -Wall nestedfunc.c
me@mybox:~/college/c++/other stuff$ ./nestedfunc 8
13
me@mybox:~/college/c++/other stuff$
我还了解到其他一些编程语言支持这些。我的问题是:嵌套函数有什么有用的用途?提前致谢。
【问题讨论】:
-
重要的是要意识到这些甚至不是远程标准,而是特定于编译器的扩展,所以如果您关心可移植性,请远离它。
标签: c nested-function