C語言關鍵字

目錄

 

一.關鍵字typedef

二.關鍵字static


 

一.關鍵字typedef


#include <stdio.h>

typedef long int32_t;//給long取了個別名,long在vs環境中長度爲4個字節,佔32位

int main(){
    int32_t a=10;
    return 0;
}

二.關鍵字static


其作用:在c中用來修飾變量和函數。

例如,下面這個程序要實現使Test()循環十次的功能。

#include <stdlib.h>
#include <stdio.h>

void Test(){
    int num=0;
    num+=1;
    printf("%d\n",num);
}
int main(){
    int count=0;//要使Test循環十次
    while(count<=9){
        Test();
        count+=1;
    }//打印結果都爲1,出現這種情況的原因是因爲num是一個局部變量
    system("pause");
    return 0;
}

要解決上述問題,可以有以下兩種辦法:

1)將num改爲全局變量。

#include <stdlib.h>
#include <stdio.h>

int num=0;//將num改爲全局變量後,打印結果爲1~10

void Test(){
    num+=1;
    printf("%d\n",num);
}
int main(){
    int count=0;//要使Test循環十次
    while(count<=9){
        Test();
        count+=1;
    }
    system("pause");
    return 0;
}

2)使用static關鍵字(修飾局部變量)。

#include <stdlib.h>
#include <stdio.h>

void Test(){
    //static修飾一個變量的時候,會讓當前變量的生命週期變成
    //全局的生命週期(跟隨整個程序)
    //並不影響變量的作用域
    static int num=0;
    num+=1;
    printf("%d\n",num);
}
int main(){
    int count=0;//要使Test循環十次
    while(count<=9){
        Test();
        count+=1;
    }//打印結果都爲1,出現這種情況的原因是因爲num是一個局部變量
    system("pause");
    return 0;
}

除此之外,static還有另外兩個作用:一是修飾全局變量時改變變量的作用域,不改變變量的生命週期;二是修飾函數時

改變其作用域,不改變其生命週期。下面將對其進行詳細的講解說明。

(一)static修飾全局變量

下面再來討論一個新的問題,在原有基礎上,新建一個文件

//全局變量命名的時候,最好加上 g_前綴,可以與局部變量有所區分
int g_count=100;

在第一次新建的文件中打印g_count

#include <stdlib.h>
#include <stdio.h>

//變量的聲明,在跨程序時要使用extern關鍵字進行變量聲明
extern int g_count;

int main(){
    printf("%d\n",g_count);
    system("pause");
    return 0;
}

結果:編譯報錯,找不到定義。

當加上extern int g_count;後編譯成功。

把第二個文件中的int g_count=100;改爲static int g_count=100;後運行程序,發現編譯報錯,說明static修飾全局變量的時候,就會導致該全局變量的作用域僅限於當前 .c文件。

(二)static用來修飾函數

文件一

int Add(int x,int y){
    int sum=x+y;
    return sum;
}

文件二

#include <stdlib.h>
#include <stdio.h>
extern int Add(int x,int y);//不加聲明時,會有警告,但是程序還可以編譯
int main(){
    printf("%d\n",Add(10,20));
    system("pause");
    return 0;
}

將文件一中的內容改爲如下內容時會發現,編譯時會報錯。

//static 修飾函數的時候,就會導致當前函數只能在當前.c文件中使用
static int Add(int x,int y){
    int sum=x+y;
    return sum;
}

下面將static的用法再做一個總結

1.修飾局部變量:修改變量的生命週期爲整個程序

2.修飾全局變量:修改變量的作用域爲當前文件

3.修飾函數:修改函數的作用域爲當前文件

以上就是對關鍵字typedef與static使用方法的知識點~續更.......

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章