static
- 全局:本文件作用域
- 局部:函数作用域。内存地址不会变动
c
/* loc_stat.c -- using a local static variable */
#include <stdio.h>
void trystat(void);
int main(void) {
int count;
for (count = 1; count <= 3; count++) {
printf("Here comes iteration %d:\n", count);
trystat();
}
return 0;
}
void trystat(void) {
int fade = 1;
static int stay = 1; // 内存地址不会变动
printf("fade = %d and stay = %d\n", fade++, stay++);
}
extern:
使用外部已经定义过的变量,
c
/* global.c -- uses an external variable */
#include <stdio.h>
int units = 0; /* an external variable */
void critic(void);
int main(void) {
extern int units; /* an optional redeclaration */
printf("How many pounds to a firkin of butter?\n");
scanf("%d", &units);
while (units != 56)
critic();
printf("You must have looked it up!\n");
return 0;
}
void critic(void) {
/* optional redeclaration omitted */
printf("No luck, chummy. Try again.\n");
scanf("%d", &units);
}
const:
关键字声明的对象,其值不能通过赋值或递增,递减来修改
c
#include <stdio.h>
void change_var_by_pointer(void) {
const int days[12] = {21, 32, 43, 54, 55, 43};
// 通过指针改数据
int* day = days;
*day = 100;
printf("days[0] = %d\n", days[0]);
}
int main(int argc, char* argv[]) {
const int nochange = 0;
const int nochange1 = 10;
const int days[12] = {21, 32, 43, 54, 55, 43};
// days[0] = 100; // err
const float* pf; // *pf
float* const pt; // pt
const float* const ptr; // ptr/*ptr
float const* pfc1; // *pfc1
const float* pfc2; // *pfc2
change_var_by_pointer();
return 0;
}
typedef:
为某一类型自定义类型,给类型定义一个别名
c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 普通类型typedef
typedef unsigned char byte;
typedef char* string;
// struct类型typedef
typedef struct person_s {
int age;
string name;
} person_t;
// 函数指针类型typedef
typedef int (*func_t)(int a, int b);
int add(int a, int b) {
return a + b;
}
void test(func_t func) { //
int ret = func(10, 20);
printf("ret = %d\n", ret);
}
int main(int argc, char* argv[]) {
// normal type
unsigned char a = 100;
byte b = 100;
char* c = "hello";
string d = "world";
// struct
struct person_s p1;
person_t p2;
// function pointer
test(add);
// typedef unsigned long clock_t; /* clock() */
// typedef long ssize_t; /* byte count or error */
// typedef long time_t; /* time() */
return 0;
}