设为首页 加入收藏

TOP

Nested Functions in C
2014-11-24 00:11:52 来源: 作者: 【 】 浏览:17
Tags:Nested Functions

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

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇tolua的tolua_toxxx系列API设计 下一篇一个通用Makefile详解

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: