如何结合使用 C 语言关键字 typeof 实现一个栈结构?下面这段代码使用双向链表实现一个栈:
#define StackInit(s) ((s)->prev = (s)->next = (s))
#define StackEmpty(s) ((s)->next == (s))
#define StackPush(s, ptr) ({ \
(s)->prev->next = (ptr); \
(ptr)->prev = (s)->prev; \
(s)->prev = (ptr); \
(ptr)->next = (s); })
#define StackPop(s) ({ \
typeof(s) top = (s)->prev; \
(s)->prev->prev->next = (s); \
(s)->prev = (s)->prev->prev; \
top->next = top->prev = 0; \
top; })
typedef struct StackItem {
struct StackItem *prev;
struct StackItem *next;
} StackItem_t;
实际使用示例,可以看到,这个简单的栈是个通用构造,Linux 内核中有很多类似的代码。
#define OFFSETOF(type, member) ((size_t)&((type*)0)->member)
#define CONTAINEROF(ptr, type, member) ( \
(type*)((char*)ptr - OFFSETOF(type, member)))
typedef struct SElem {
int ord;
struct StackItem node;
} SElem_t;
#define SElemEntry(ptr, type, member) CONTAINEROF(ptr, type, member)
int main()
{
StackItem_t s;
StackInit(&s);
SElem_t item;
StackPush(&s, &item.node);
StackItem_t *e = StackPop(&s);
SElem_t *x = SElemEntry(e, SElem_t, node);
// x:0x7fff55e59b00 item:0x7fff55e59b00
printf("x:%p item:%p\n", x, &item);
return 0;
}
参考资料:
转载请注明出处:
This work is licensed under a MIT License.