现在的位置: 首页 > 综合 > 正文

C 语言几个绝招

2012年08月19日 ⁄ 综合 ⁄ 共 805字 ⁄ 字号 评论关闭

1.        符号展开连接:

#define  CAT_TOKEN_1(t1, t2)  t1##t2

#define  CAT_TOKEN(t1, t2)  CAT_TOKEN_1(t1,t2)

CAT_TOKEN_1 直接将 t1t2连接成 t1t2,而

CAT_TOKEN t1t2展开后再连接,如:

#define  t1  I_am_

#define  t2  lei_peng

CAT_TOKEN_1(t1, t2) 的结果是  t1t2

CAT_TOKEN(t1, t2) 的结果是  I_am_leipeng

CAT_TOKEN 相当有用。

2.        0转化为0,而将非零转化为 1,可以转化指针

#define convert_bool(x) (!!(x))

3.        编译时断言:

#define COMPILE_ASSERT(x)  /

enum { CAT_TOKEN (comp_assert_, __LINE__) = 1 / !!(x) };

// 或者

#define COMPILE_ASSERT_2(x)  /

void CAT_TOKEN(comp_assert_fun_,__LINE__)  (int x[][x]);

4.        定义 Handle类型

#define  DEFINE_HANDLE_TYPE(handle_type)  /

struct param_##handle_type;     /

typedef  void  (*handle_type )(struct param_##handle_type);

Handle 定义为函数指针主要有一个好处:就是禁止了对 Handle 的加减,防止了一些小错误的发生。

5.        定义union中的匿名 struct

struct  my_type {

union {

        struct {   ….} u1;

        struct {   ….} u2;

        struct {   ….} u3;

     };

};

 

 

抱歉!评论已关闭.