关于 C 语言的嵌套函数

/ 0评 / 0

考虑一个这样的函数:


int f() {
  int foo = 10;
  int bar = 20;
  int g(int param) {
    foo += 2;
    return param + foo + bar;
  }
  return g(10); // 42
}

似乎很不寻常。这个函数在其内部声明了一个函数,在里面的函数似乎还可以使用和更改外层函数的局部变量。

当然,这段代码不是标准 C. 这是 GNU C 扩展——嵌套函数 (Nested function)。

嵌套函数能够帮我们简化一些繁琐的操作。考虑数组迭代函数:


void array_iterate(void** array, size_t len, void (*function)(void*)) {
  for(size_t i = 0; i < len; i++){
    function(array[i]);
  }
}

借助嵌套函数,我们可以这样写:

void fancy_operation(int* array, size_t len, int iter_param) {
  void plus_n(void* num) {
    printf("%d\n", iter_param + ((int) num));
  }
  array_iterate((void**) array, len);
}

还可以这样写:

void fancy_operation2() {
  int value = 1;
  int array[] = {1, 2, 3, 4, 5};
  for(; value < 5; value++) {
    void f(void* x) {
      printf("%d\n", value * ((int) x));
    }
    array_iterate((void**) array, 5, f);
  }
}

当然,这些操作看起来并没有什么好玩的——它们甚至可以直接转换成普通的函数。其实任何一个嵌套函数都可以通过全局变量改写成为普通函数。不过嵌套函数的存在似乎可以给代码加一种整洁的错觉。

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Your comments will be submitted to a human moderator and will only be shown publicly after approval. The moderator reserves the full right to not approve any comment without reason. Please be civil.