Review of C——extern、typedef

最后发布时间:2020-12-05 20:41:44 浏览量:

Static variables

#include <stdio.h>

static int count = 5;
void func();
void main(){
    while(count--){
        func();
        // printf("%d",i); no access
    }
}
void func(){
    static int i = 5;
    i++;
    printf("i= %d count=%d\n",i,count);
}
i= 6 count=4
i= 7 count=3
i= 8 count=2
i= 9 count=1
i= 10 count=0

extern global variable

automatic variable and extern global

  • main.c
#include <stdio.h>

void func();
int x=50;
int main(){
    //printf("x= %d \n",x);
    func();
    return 0;
}
  • func.c
#include <stdio.h>
extern int x; // extern宣告x为global variable
void func(){
    printf("x= %d \n",x);
}

typedef: a new name for a type

#include <stdio.h>

typedef int Integer;
Integer x=50;

typedef struct Books
{
    char title[50];
} Book;

int main(){
    Book book1 = {"zs"};
    struct Books book2 = {"ls"};

    printf("x = %d\n",x);
    printf("book1 = %s\n",book1.title);
    printf("book1 = %s\n",book2.title);
    return 0;
}

typedef Function Pointer

#include <stdio.h>

typedef int (*t_somefunc)(int, int);

int produce(int a, int b){
    return a*b;
}

int main(){
    t_somefunc afunc = &produce;
    int x = afunc(5,6);
    int y = (*afunc)(6,6);
    printf("x = %d\n",x);
    printf("y = %d\n",y);
    return 0;
}