linux内核中的C语言常规算法(前提:你的编译器要支持typeof和type)
2016-01-21 20:51
309 查看
学过C语言的伙伴都知道,曾经比较两个数,输出最大或最小的一个,或者是比较三个数,输出最大或者最小的那个,又或是两个数交换,又或是绝对值等等,其实这些算法在linux内核中通通都有实现,以下的代码是我从linux内核源码的kernel.c中抠出来的代码,我们来看看:
我们直接上代码:
这些算法在内核中通常用宏的规格来实现,关于C语言很多算法,其实在linux内核中几乎都有,比如链表,树,图,排序,字符串,加密等等的算法和数组结构都有实现,能够深入的去理解linux内核,对学习C语言是非常有帮助的。
我们直接上代码:
#include <stdio.h> #include <stdlib.h> /* * min()/max() macros that also do * strict type-checking.. See the * "unnecessary" pointer comparison. */ //比较两个数,如果x>y,输出y,否则输出x #define min(x,y) ({ \ typeof(x) _x = (x); \ typeof(y) _y = (y); \ (void) (&_x == &_y); \ _x < _y ? _x : _y; }) //比较两个数,如果x>y,输出x,否则输出y #define max(x,y) ({ \ typeof(x) _x = (x); \ typeof(y) _y = (y); \ (void) (&_x == &_y); \ _x > _y ? _x : _y; }) //比较三个数的大小 ,输出最小的一项 #define min3(x,y,z) ({ \ typeof(x) _min1 = (x) ; \ typeof(y) _min2 = (y) ; \ typeof(z) _min3 = (z) ; \ (void) (&_min1 == &_min2) ; \ (void) (&_min1 == &_min3) ; \ _min1 < _min2 ? (_min1 < min3 ? _min1 : _min3) ; \ (_min2 < _min3 ? _min2 : _min3) ;} ) //比较三个数的大小 ,输出最大的一项 #define max3(x,y,z) ({ \ typeof(x) _max1 = (x) ; \ typeof(y) _max2 = (y) ; \ typeof(z) _max3 = (z) ; \ (void) (&_max1 == &_max2) ; \ (void) (&_max1 == &_max3) ; \ _max1 > _max2 ? (_max1 > max3 ? _max1 : _max3) ; \ (_max2 > _max3 ? _max2 : _max3) ;} ) //输出绝对值 #define abs(x) ({ \ int __x = (x); \ (__x < 0) ? -__x : __x; \ }) //交换两个数 #define swap(a,b) \ do{typeof(a) __tmp = (a); (a) = (b) ; b = (__tmp) ;}while(0) int main(void) { int ret = 0 ; ret = max(1,2); printf("%d\n",ret); printf("%d\n",abs(-100)); int a = 2 ; int b = 3 ; swap(a,b); printf("%d %d\n",a,b); return 0 ; }运行结果如图所示:
这些算法在内核中通常用宏的规格来实现,关于C语言很多算法,其实在linux内核中几乎都有,比如链表,树,图,排序,字符串,加密等等的算法和数组结构都有实现,能够深入的去理解linux内核,对学习C语言是非常有帮助的。
相关文章推荐
- linux内核中的C语言常规算法(前提:你的编译器要支持typeof和type)
- 理解和使用Linux的硬件抽象层HAL
- Linux_定制自己的vim
- Linux上搭建Hadoop2.6.3集群以及WIN7通过Eclipse开发MapReduce的demo
- linux系统构架 - LB集群之LVS介绍
- Linux mysql 启动
- CentOS 7源码安装LNMP环境
- 记录一下,linux工程调试开发应用!
- Centos搭建SVN服务器及配置文件(主要讲配置)
- linux(centos6.5)系统中忘记mysql root的密码的解决方法
- linux分析和排查系统故障
- This howto guide shows you’ll how to enable EPEL repository under RHEL/CentOS 6/5 to install additio
- linux常识小记
- VM添加虚拟网卡后不能上网
- linux进程前后台切换及任务计划
- linux中的几点安全
- Linux硬链接和软链接(符号链接)
- Linux学习awk命令
- Capture images using V4L2 on Linux
- linux中怎样设置dhcpd