1. 程式人生 > >C語言auto、register、static、extern關鍵字

C語言auto、register、static、extern關鍵字

1.auto

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

int a = 0;

void show(){
    a++;
    printf("hello: %d\n",a);
}

void main(int *argv, char *args[]){

    show();
/**
Auto變數:
區域性變數不作任何說明,都作為自動變數auto,及動態儲存的。Auto可省略。
*/
    volatile unsigned auto int b = 10;

}
2.register
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int a = 0;

void show(){
    a++;
    printf("hello: %d\n",a);
}

void main(int *argv, char *args[]){

    show();
/**
Register變數:暗示編譯程式相應的變數將將被頻繁使用,如果可能的話,
應將其儲存在CPU的暫存器中,以指加快其存取速度,有幾點使用限制:
1 register變數必須是能被CPU暫存器所接受的型別
2為register變數可能不存放在記憶體中,所以不能用取址符運算子“& ”來獲取取址符運算子
3只有區域性變數和形參可以作為register變數,全域性變數不行
4 80x86系列CPU最多可使用的register變數數目有限。int型可使用8個通用暫存器
5 靜態變數不能定義為register。
*/
    register int b = 10;
}
3.static
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int A;

void show(){
    volatile static int a ;//靜態區域性變數(static) 靜態區域性變數定義時前面加static關鍵字。
    a++;
    f1(a);
    f2(a);
    //printf("show: B = %d\n",B);
}

void main(int *argv, char *args[]){

    show();
    show();
    show();
    show();
    int c;
    static int b = 10;
}

/**
//head1.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
static int B ;
int A;
void f1(int a){

    A++,B++;
    printf("head1.h:f1(%d), A = %d, B = %d\n",a,A,B);

}

//head2.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
static int B;
int A;
void f2(int a){

    A += 2, B += 2;
    printf("head2.h:f2(%d), A = %d, B = %d\n",a,A,B);

}
*/

/**
-bash-4.1$ gcc -o a Demo.c head*.c
-bash-4.1$ ./a
head1.h:f1(1), A = 1, B = 1
head2.h:f2(1), A = 3, B = 2
head1.h:f1(2), A = 4, B = 2
head2.h:f2(2), A = 6, B = 4
head1.h:f1(3), A = 7, B = 3
head2.h:f2(3), A = 9, B = 6
head1.h:f1(4), A = 10, B = 4
head2.h:f2(4), A = 12, B = 8
-bash-4.1$ 

*/
4.extern
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void main(int *argv, char *args[]){

    extern const int num;
    extern void show();
    show();
    printf("main: num = %d\n",num);
    
}

/**
//extern.c

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

const int num = 3;
void show(){
    printf("show: num = %d\n",num);
}


*/