代码之家  ›  专栏  ›  技术社区  ›  pr1268

C中嵌套函数有什么好的用途吗?

  •  2
  • pr1268  · 技术社区  · 15 年前

    我在某个地方读到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$
    

    我也读过一些其他编程语言支持这些。我的问题是:嵌套函数有什么有用的用途?提前谢谢。

    4 回复  |  直到 14 年前
        1
  •  2
  •   Frédéric Hamidi    15 年前

    嵌套函数提供 encapsulation 通过 lexical scope .

    在你的例子中, G() 只能通过 F() 以及 F() .

        2
  •  3
  •   jilles    15 年前

    嵌套函数可以访问外部函数的局部变量。类似于闭包,您可以将指针指向嵌套函数并将此指针传递给其他函数,嵌套函数将可以访问当前调用的局部变量(如果此调用已返回,则会发生错误)。因为C运行时系统不是为此而设计的,所以函数指针通常只是指向函数的第一条指令的指针,而指向嵌套函数的指针只能通过在堆栈上编写一些代码并传递指向该堆栈的指针来完成。从安全角度来看,这是个坏主意。

    如果要使用嵌套函数,请在运行时系统中使用对其具有适当支持的语言。为了在C语言中实现类似的结果,将“外部函数的局部变量”放在上下文结构中并手动传递。

        3
  •  1
  •   Greg Hewgill    15 年前

    通常,嵌套函数通常是一个helper函数,它只在另一个函数中使用。有点像 static 函数(具有文件作用域)但更本地化(仅限于函数作用域)。

    嵌套函数不是标准的C语言,因此在该语言中使用它们几乎没有理由。

        4
  •  0
  •   Mariy    15 年前

    在其他编程语言(例如Python、Ruby)中,函数是第一类对象。你有 closures 它们是强大的抽象概念。在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)
    

    那就是咖喱装饰器,它接受一个函数并使它变成咖喱。