C - 基础 - C预处理器和C库

#define

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdio.h>

#define TWO 2
#define OW "woow"
#define FOUR TWO * TWO
#define PX printf("X is %d \n",x) // 宏 定义函数
#define FMT "X is %d \n" // 定义格式模版
#define SQUARE(X) X*X // 带参数宏
#define XNAME(n) x ## n // ## 运算符
int main(int argc, char *argv[])
{
int x = TWO;
PX;
x = FOUR;
printf(FMT, x);
printf("square(2) is %d \n", SQUARE(2));
char * XNAME(4) = "x4";
printf("预处理器粘合剂 ##运算符:%s .\n", XNAME(4));

return 0;
}

其他指令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <stdio.h>

#pragma c9x on // 编译器设置都可以定义 强大到没朋友
#define TWO 2
#undef TWO // 取消宏
#ifdef TWO // 条件编译 相反为 #ifndef
#define TWO 23
#else
#define TWO 3
#endif
int main(int argc, char *argv[])
{
#ifdef TWO
printf("TOW is %d \n", TWO);
#endif // TWO

#if TWO == 3 // 条件判断
printf("oh , 3 \n");
#elif TWO ==2
printf("oh , 2 \n");
#endif
return 0;
}

内联函数

就是不需要声明,直接定义然后调用的使用inline修饰函数,无法获取地址,可放在头文件供外部调用。
相当于将方法体拷贝到调用处。

C库

数学库 math.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <stdio.h>
#include <stdlib.h>
#include <math.h> // 数学库
void bye();
void print_array(const int array[] , int size);
int my_compar(const void * p1, const void * p2); // 自定义 排序比较器
int main(int argc, const char * argv[]) {
atexit(bye); // 程序结束时回调函数
double angle = 30.0 * 3.14/180; // 角度是这么定义的。。要跪
double x = sin(angle);
printf("sin(%f) = %0.2f \n",angle,x);

int array[3] = {4,2,3};
print_array(array,3);
int (* fp)(const void *, const void *) = my_compar;
qsort(array, 3, sizeof(int),fp); // 排序,传入自定义比较器
print_array(array,3);
return 0;
}
void bye()
{
printf("bye \n");
}
int my_compar(const void * p1, const void * p2)
{
const int * p3 = (const int *)p1;
const int * p4 = (const int *)p2;
if(*p3 > *p4)return 1;
else if(*p3 < *p4)return -1;
else return 0;
}
void print_array(const int array[] , int size)
{
for(int i = 0 ; i < size ; i++)
{
printf("%d",array[i]);
}
printf("\n");
}

推荐文章