Nested Functions in C

2014-11-24 00:11:52 · 作者: · 浏览: 23

Nested Functions 又称closure,属于functional language中的概念,一直以为C中是不支持closure的,现在看来我错了,不过C标准中是不支持的,而GCC支持。

既然GCC支持了closure,那么 lexical scoping自然也支持了,同时在C中label也是可以在nested functions中自由跳转的,还有nested function可作为返回地址被外部调用,这与lisp中的概念都一致。

C代码
foo (double a, double b)
{
double square (double z) { return z * z; }

return square (a) + square (b);
}


bar (int *array, int offset, int size)
{
int access (int *array, int index)
{ return array[index + offset]; }
int i;
/* ... */
for (i = 0; i < size; i++)
/* ... */ access (array, i) /* ... */
}


bar (int *array, int offset, int size)
{
__label__ failure;
int access (int *array, int index)
{
if (index > size)
goto failure;
return array[index + offset];
}
int i;
/* ... */
for (i = 0; i < size; i++)
/* ... */ access (array, i) /* ... */
/* ... */
return 0;

/* Control comes here from access
if it detects an error. */
failure:
return -1;
}


摘自 bookjovi