參數傳遞采用按值傳遞
ADT:abstract data type,抽象數據類型
c可以用於設計與實現抽象數據類型,因為它可以限制函數和數據定義的作用域,這種技巧也稱為黑盒設計
user.h
#define MAXLEN 3 struct UserClz { char *name; char *phone; char *address; }; typedef struct UserClz User; /* *接函數 *通地名稱查找地址 */ char const * lookupAddress(char const *name); /* *接函數 *通地名稱查找電話 */ char const * lookupPhone(char const *name);
user.c#include "user.h" #include#include /* *限制訪問范圍 */ static User users[MAXLEN]={ {"user1","111","aaa"}, {"user2","222","bbb"}, {"user3","333","ccc"} }; void init(){ int j=0; for(j=0;j name,name)==0){ return pu+i; } } return NULL; } char const * lookupPhone(char const *name){ User const *pu; pu=getUserByName(name); if(pu!=NULL){ return pu->phone; }else { return NULL; } } char const * lookupAddress(char const *name){ User const *pu; pu=getUserByName(name); if(pu!=NULL){ return pu->address; }else { return NULL; } }
main.c#include#include "user.c" void main(){ init(); printf("phone=%s\n",lookupPhone("user1")); printf("address=%s\n",lookupAddress("user2")); }
以上就是黑盒的例子,墨盒的功能通過規定的接口訪問模塊,接口函數lookupPhone與lookupAddress,
用戶不能直接訪問和模塊實現相關的數據,如:users,getUserByName,它們被聲明為static
求菲波那契數
#includeint fn(int n){ if(n<=2) return 1; return fn(n-1)+fn(n-2); } void main(){ printf("result:%d\n",fn(5));// result:5 }
過程圖