1. 程式人生 > >一些實用的C語言小技巧

一些實用的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無法在巨集當中做到型別檢查(據我所知是這樣的),所以安全起見上述程式碼沒有這樣做。