一些实用的C语言小技巧

静态断言

#define STATIC_ASSERT(expr) (\
(void)sizeof(char[1-2*!!!(expr)]))

当然还有其他实现方法,但这种无疑是最简单、最通用的方法了

获取偏移量

#define offsetof(type, member) (\
 (size_t)&((type*)0->menber) )

一般来说,这个宏会在<stddef.h>文件中被定义,当然其实现形式会随编译器的不同而变化

获取容器地址

#define container_of(ptr, type, member) (\
 (type *)( (char *)(ptr) - offsetof(type,member) ) )

这个宏常见于Linux内核,而它通常的定义如下:

     /** 
     * container_of - cast a member of a structure out to the containing structure 
     * @ptr:        the pointer to the member. 
     * @type:       the type of the container struct this is embedded in. 
     * @member:     the name of the member within the struct. 
     * 
     */  
    #define container_of(ptr, type, member) ({                      \  
            const typeof( ((type *)0)->member ) *__mptr = (ptr);    \  
            (type *)( (char *)__mptr - offsetof(type,member) );})  

仔细琢磨便可发现,上述定义中的第一个语句实际上没有实现任何功能。而且,上述定义中使用了GNUC的拓展语法,不属于标准C语言的范畴。然而,第一个定义却是完全符合标准C语言语法,但相较于第二种定义失去了类型检查的功能,变得更加不安全。

获取数组元素数目

#define ARRAY_SIZE(a) ( sizeof(a)/sizeof((a)[0]) )

同样来源于Linux内核的宏,同样为了适应标准C做了阉割。在gcc环境下,更加安全的定义如下:

#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) \
    +sizeof(typeof(int[1-2*!!__builtin_types_compatible_p(typeof(arr),\
         typeof(&arr[0]))]))*0)

同理,利用GNUC的typeof关键字和内建函数,判断arr和&arr[0]类型是否相同,相同则会导致数组长度为负数,实现静态断言,避免在这里错误地使用指针作为宏的参数。所以,当你使用这个宏的时候,请务必谨慎!同时还要注意,这个宏的名称有歧义,我更乐意将它叫做member_of或者number_of因为它返回的是数组的元素个数,而不是数组的大小。

头文件保护符

这个其实相当常见,一般格式如下:

#ifndef __XXX_H__
#define __XXX_H__
#endif

从中拓展出来的技巧还有:

#ifndef XXX_GLOBAL
#define XXX_EXT extern
#else
#define XXX_EXT
#endif
#ifndef XXX_GLOBAL
#define INIT(val, init) (val)
#else
#define INIT(val, init) (val) = (init)
#endif

还是比较有用的,都是条件编译的灵活运用。

符号转字符串

#define _STR(x) #x

这个配合字符串的拼接,能够完成一些相当便利的操作。示例如下:

#define sys_call(n) __asm volatile("svc #"#n)

可以说非常清爽便利了。

符号拼接

#define _str_spice(tkn1, tkn2) tkn1##tkn2
#define str_spice(tkn1, tkn2) _str_spice(tkn1, tkn2)

这样写是为了进行宏的展开。

泛型编程

借助宏,还可以实现泛型编程,实现c++当中的模版的部分功能。示例如下:

/*
 * heap.h
 *
 *      Author: SMS
 */
#ifndef __HEAP_H__
#define __HEAP_H__

#include <stdint.h>
#include <stdbool.h>

#define _str_spice(tkn1, tkn2) tkn1##tkn2
#define str_spice(tkn1, tkn2) _str_spice(tkn1, tkn2)

#define __template(type, tplt) str_spice(type, str_spice(_, tplt))

#ifdef __cplusplus
extern "C" {
#endif  /* __CPLUSPLUS */

#ifndef heap_type
#define heap_type int
#endif

typedef bool(*compare_t)(heap_type*, heap_type*);

static inline void
__template(heap_type, heap_swap)(heap_type *a, heap_type *b)
{
    heap_type t;
    t = *a;
    *a = *b;
    *b = t;
}

static inline void
__template(heap_type, heap_build)(heap_type a[],
        compare_t func,
        unsigned bgn,
        unsigned end)
{
    heap_type t = a[bgn];
    unsigned i;
    for(i=(bgn<<1)+1; i<=end; bgn=i, i=(i<<1)+1)
    {
        if(i<end && !func(&a[i], &a[i+1]))
            i++;
        if(func(&t, &a[i]))
            break;
        a[bgn] = a[i];
        a[i] = t;
    }
}

static inline void
__template(heap_type, heap_adjast)(heap_type a[],
        compare_t func,
        unsigned bgn,
        unsigned end)
{
    heap_type t = a[end];
    unsigned i;
    for(i=(end-1)>>1; i>=bgn && end!=bgn; end=i, i=(i-1)>>1)
    {
        if(!func(&t, &a[i]))
            break;
        a[end] = a[i];
        a[i] = t;
    }
}

static inline void
__template(heap_type, heap_sort)(heap_type a[],
        compare_t func,
        unsigned len)
{
    unsigned i = (len>>1)-1;
    for(; i<(unsigned)-1; i--)
        __template(heap_type, heap_build)(a, func, i, len-1);

    for(i=len-1; i!=0; i--)
    {
        __template(heap_type, heap_swap)(&a[0], &a[i]);
        __template(heap_type, heap_build)(a, func, 0, i-1);
    }
}

static inline void
__template(heap_type, heap_push)(heap_type a[],
        compare_t func,
        unsigned len,
        heap_type *data)
{
    a[len-1] = *data;
    __template(heap_type, heap_adjast)(a, func, 0, len-1);
}

static inline void
__template(heap_type, heap_pop)(heap_type a[],
        compare_t func,
        unsigned len,
        unsigned index)
{
    a[index] = a[len-1];
    __template(heap_type, heap_build)(a, func, index, len-1);
}

#ifdef __cplusplus
}
#endif /* __CPLUSPLUS */

#endif /* __HEAP_H__ */

其实可以更进一步,将函数中的函数指针参数也作为一个宏参数,让上面的代码看起来更像c++的模版。但是标准C无法在宏当中做到类型检查(据我所知是这样的),所以安全起见上述代码没有这样做。

  • 5
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值