- 註冊時間
- 2006-10-8
- 最後登錄
- 2019-6-20
- 主題
- 查看
- 積分
- 1306
- 閱讀權限
- 110
- 文章
- 1388
- 相冊
- 0
- 日誌
- 1
   
狀態︰
離線
|
不僅變數的 宣告或定義 具有 區域性與全域性, 事實上任意一 辨識體(物件) 如 struct、 typedef、 enum、 巨集的宣告、 函數的定義等,其 使用範圍的規則 也相同。
C 程式 函數的定義不像 Pascal,函數 不能 定義在 另一個函數之內。因此,函數都具有 全域性。 一般而言, 我們會宣告一個函數 在 檔頭或 在一個 block 的開頭,如:
例 4.
int square(int i); 或 main()
main() { int square(int i);
{ int i=10,j=2; int i=10,j=2;
j=square(i); j=square(i);
} }
int square() int square(int i)
{return i*i;} {return i+i;}
通常 一個程式的設計,可 能會因性質的不同 而 將 程式碼 分散於 不同的檔案,對於一些常數的定義, 全域變數的宣告, 函數的宣告, 資料型態的設定 都放在 檔頭檔,以 #include 的方式 來達到 宣告的一致性。我們將於第 10 章 來 介紹 程式設計的一些技巧。
例 5. 設檔案 file.txt 含下列內容:
#include< stdio.h >
struct point {int x,y;};
struct rect {point topLeft, bottomRight};
int pointInRect(struct point, stuct rect);
extern point currentLoc;
設檔案 file.c 含下列內容:
#include "file.txt"
point currentLoc;
int pointInRect(struct point p, stuct rect r)
{ int x1,x2,y1,y2;
if(r.topLeft.x < r.bottomRight.x)
{ x1=r.topLeft.x; x2=r.bottomRight.x;}
else
{ x2=r.topLeft.x; x1=r.bottomRight.x;}
if(r.topLeft.y < r.bottomRight.y)
{ y1=r.topLeft.y; y2=r.bottomRight.y;}
else
{ y2=r.topLeft.y; y1=r.bottomRight.y;}
if(x1 <= p.x && p.x <= x2 && y1 <=p.y && p.y <= y2)
return 1;
else return 0;
}
設檔案 main.c 含下列內容
#include "file.txt"
main()
{ struct rect r;
r.topLeft.x=10; r.topLeft.y=10;
r.bottomRight.x=20; r.bottomRight.y=20;
scanf("%d %d", ¤tLoc.x, ¤tLoc.y);
if(pointInRect(currentLoc,r))
printf("in the rectangle\n");
else
printf("not in the rectangle\n");
}
說明:
檔案 file.c 含 全域變數 currentLoc 的定義。
檔案 file.txt 含全域變數 currentLoc 的宣告,即 extern point currentLoc,其中 extern 表示 全域變數定義 於它處。
檔案 file.txt 含函數 pointInRect 的宣告,即 int pointInRect(struct point,struct rect);。
資料型態 struct point 及 struct rect 都宣告於檔案 file.txt 中, file.c 與 main.c 皆有 #include 指令 "file.txt",因此可直接使用 struct point 及 struct rect。
|
|