variable的modifier定義其特性,這次討論static與extern:

static variable: 其值是會保留在記憶體的,不隨著離開其scope而消失 (只initialize一次)。

extern variable: 該變數已在其他地方(包括其他file)被定義過了,存取的方式是先宣告為extern,再來存取。

看例子:

1. static variable:

#include <stdio.h>
int f1()
{
    static int a=0;
    a++;
    printf("The value of a is %d\n", a);
    return 0;
}
int main()
{
    int i;
    for (i=0;i<=5;i++)
        f1();
        return 0;
}


result:

The value of a is 1
The value of a is 2
The value of a is 3
The value of a is 4
The value of a is 5
The value of a is 6


2. extern variable:

f1.c

#include <stdio.h>

int a=100;

main.c

#include <stdio.h>
int main()
{
        extern int a;
        printf("The value of a is %d\n",a);
        return 0;
}

result:

The value of a is 100


定義在主體以外的為global variable,通常是定義常數用的。將static variable定義為 global,其特性是一樣的,但 scope則是該文件。function也可以是 static, scope也是該文件,一個好處是可避免function名稱相同,因為static function其 scope只在該file,即使在其他file用extern仍然是invisible。

 

arrow
arrow
    全站熱搜

    kezeodsnx 發表在 痞客邦 留言(0) 人氣()