bookjovi 发表于 2013-1-26 12:29:59

Nested Functions in C

 
Nested Functions 又称closure,属于functional language中的概念,一直以为C中是不支持closure的,现在看来我错了,不过C标准中是不支持的,而GCC支持。
 
既然GCC支持了closure,那么 lexical scoping自然也支持了,同时在C中label也是可以在nested functions中自由跳转的,还有nested function可作为返回地址被外部调用,这与lisp中的概念都一致。
 
 
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; }       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;         }       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;   }
页: [1]
查看完整版本: Nested Functions in C