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)
嵌套函数可以访问外部函数的局部变量。有点像闭包,您可以获取指向嵌套函数的指针并将该指针传递给其他函数,并且嵌套函数将可以访问当前调用的局部变量(如果此调用已经返回,则会发生不好的事情)。因为 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.
嵌套函数通过 封装 .wikipedia.org/wiki/Scope_%28programming%29#Lexical_scoping" rel="nofollow">词汇范围。
在您的示例中,
G()
只能由F()
以及F()
中定义的其他函数调用。Nested functions provide encapsulation through lexical scope.
In your example,
G()
can only be called byF()
and by other functions defined withinF()
.一般来说,嵌套函数通常是一种辅助函数,仅在另一个函数内部使用。它有点像静态函数(具有文件作用域),但更加本地化(仅函数作用域)。
嵌套函数不是标准 C,因此没有理由在该语言中使用它们。
In general, a nested function is usually a helper function, which is only used inside one other function. It's sort of like a
static
function (with file scope) but even more localised (only function scope).Nested functions are not standard C, so there's little reason to use them in that language.
在其他编程语言(例如 Python、Ruby)中,函数是第一类对象。你有闭包,这是强大的抽象概念。在 python 中你可以这样做:
这是 curry 装饰器,它接受一个函数并使其咖喱化。
In other programming languages (like Python, Ruby for example) functions are first class objects. You have closures which are powerful abstraction concept. In python you can do this:
That is curry decorator which takes a function and makes it curried.