程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C >> 關於C >> Nested Functions in C

Nested Functions in C

編輯:關於C

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

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved