C 中的嵌套函数有什么用处?

发布于 2024-10-04 22:57:08 字数 617 浏览 1 评论 0 原文

我在某处读到嵌套函数在 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$

我还了解到其他一些编程语言支持这些代码。我的问题是:嵌套函数有什么用处?提前致谢。

I read somewhere that nested functions are permissible in C (at least the GNU compiler allows it). Consider the following code:

/* 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;
}

Compiling and running:

gcc -o nestedfunc -O2 -s -Wall nestedfunc.c
me@mybox:~/college/c++/other stuff$ ./nestedfunc 8
13
me@mybox:~/college/c++/other stuff$

I've also read that some other programming languages support these. My question is this: What useful purpose does a nested function have? Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

撩发小公举 2024-10-11 22:57:08

嵌套函数可以访问外部函数的局部变量。有点像闭包,您可以获取指向嵌套函数的指针并将该指针传递给其他函数,并且嵌套函数将可以访问当前调用的局部变量(如果此调用已经返回,则会发生不好的事情)。因为 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.

遮云壑 2024-10-11 22:57:08

嵌套函数通过 封装 .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 by F() and by other functions defined within F().

红ご颜醉 2024-10-11 22:57:08

一般来说,嵌套函数通常是一种辅助函数,仅在另一个函数内部使用。它有点像静态函数(具有文件作用域),但更加本地化(仅函数作用域)。

嵌套函数不是标准 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.

梦行七里 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 装饰器,它接受一个函数并使其咖喱化。

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:

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)

That is curry decorator which takes a function and makes it curried.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文