C 中的嵌套函数有什么用处?
我在某处读到嵌套函数在 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$
我还了解到其他一些编程语言支持这些代码。我的问题是:嵌套函数有什么用处?提前致谢。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(4)
梦行七里 2024-10-11 22:57:08
在其他编程语言(例如 Python、Ruby)中,函数是第一类对象。你有闭包,这是强大的抽象概念。在 python 中你可以这样做:
def curry(func):
from inspect import getfullargspec
args = getfullargspec(func)
num_args = len(args[0])
def new_func(list_args, *args):
l = len(list_args) + len(args)
nl = list_args + list(args)
if l > num_args:
raise TypeError("Too many arguments to function")
elif l == num_args:
return func(*nl)
else:
return lambda *new_args: new_func(nl, *new_args)
return lambda *args: new_func([], *args)
这是 curry 装饰器,它接受一个函数并使其咖喱化。
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
更多
嵌套函数可以访问外部函数的局部变量。有点像闭包,您可以获取指向嵌套函数的指针并将该指针传递给其他函数,并且嵌套函数将可以访问当前调用的局部变量(如果此调用已经返回,则会发生不好的事情)。因为 C 运行时系统不是为此设计的,所以函数指针通常只是指向函数第一条指令的指针,而指向嵌套函数的指针只能通过在堆栈上编写一些代码并将指针传递给该代码来完成。从安全角度来看,这是一个坏主意。
如果您想使用嵌套函数,请使用具有适当支持它们的运行时系统的语言。要在 C 中实现类似的结果,请将“外部函数的局部变量”放入上下文结构中并手动传递它。
Nested functions can access the outer function's locals. Somewhat like closures, you can take a pointer to a nested function and pass this pointer to other functions, and the nested function will have access to the current invocation's locals (bad things happen if this invocation has already returned). Because the C runtime system is not designed for this, a function pointer is generally just a pointer to the first instruction of the function and pointers to nested functions can only be done by writing some code on the stack and passing a pointer to that. This is a bad idea from a security perspective.
If you want to use nested functions, use a language with a runtime system with proper support for them. To achieve a similar result in C, put "the outer function's locals" in a context structure and pass this along manually.