文章转自 淘宝核心团队博客 http://rdc.taobao.com/blog/cs/?p=1675
1. 优雅地使用链表
struct list_head {
struct list_head *next, *prev;
};
#define LIST_HEAD_INIT(name) { &(name), &(name) }
2) 链表使用者定义:
struct user_t {
data domain;
struct list_head node;
};
struct list_head g_user_list = LIST_HEAD_INIT(g_user_list);
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#define container_of(ptr, type, member) ({
const typeof(((type *)0)->member) * __mptr = (ptr);
(type *)((char *)__mptr - offsetof(type, member)); })
struct user_t* next = container_of(&(g_user_list.next->node), struct user_t, node);
这里用到了container_of,container_of又用到了offsetof。offsetof是通过将结构体起始地址强制对齐到0来计算出node和起始地址的偏移offset;而container_of在node地址基础上减去offset得到user_t结构体的地址并返回user_t。
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
long __builtin_expect (long EXP, long C)
__asm__ __volatile__(
" lock ;n"
" addl %1,%0 ;n"
: "=m" (my_var) //output
: "ir" (my_int), "m" (my_var) //input
: //modify /* no clobber-list */
);
struct line {
int length;
char contents[0];
};
struct line *thisline = (struct line *)malloc (sizeof (struct line) + this_length);
thisline->length = this_length;
只有GNU C才支持的特性,对于定义不确定长度的数组非常有用。
a = x ? : y;
a = x ? x : y;