The most useful user-made C-macros (in GCC, also C

2020-05-11 09:51发布

What C macro is in your opinion is the most useful? I have found the following one, which I use to do vector arithmetic in C:

#define v3_op_v3(x, op, y, z) {z[0]=x[0] op y[0]; \
                               z[1]=x[1] op y[1]; \
                               z[2]=x[2] op y[2];}

It works like that:

v3_op_v3(vectorA, +, vectorB, vectorC);
v3_op_v3(vectorE, *, vectorF, vectorJ);
...

18条回答
Explosion°爆炸
2楼-- · 2020-05-11 10:05

This one is from linux kernel (gcc specific):

#define container_of(ptr, type, member) ({                  \
const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
    (type *)( (char *)__mptr - offsetof(type,member) ); })

Another missing from other answers:

#define LSB(x) ((x) ^ ((x) - 1) & (x))   // least significant bit
查看更多
▲ chillily
3楼-- · 2020-05-11 10:05

Just the standard ones:

#define LENGTH(array) (sizeof(array) / sizeof (array[0]))
#define QUOTE(name) #name
#define STR(name) QUOTE(name)

but there's nothing too spiffy there.

查看更多
甜甜的少女心
4楼-- · 2020-05-11 10:07
#define COLUMNS(S,E) [ (E) - (S) + 1 ]


struct 
{
    char firstName COLUMNS ( 1, 20);
    char LastName  COLUMNS (21, 40);
    char ssn       COLUMNS (41, 49);
}

Save yourself some error prone counting

查看更多
▲ chillily
5楼-- · 2020-05-11 10:07

Checking whether a floating point x is Not A Number:

#define ISNAN(x) ((x) != (x))
查看更多
爷的心禁止访问
6楼-- · 2020-05-11 10:12

Pack bytes,words,dwords into words,dwords and qwords:

#define ULONGLONG unsigned __int64
#define MAKEWORD(h,l) ((unsigned short) ((h) << 8)) | (l)
#define MAKEDWORD(h,l) ((DWORD) ((h) << 16)) | (l)
#define MAKEQWORD(h,l) ((ULONGLONG)((h) << 32)) | (l) 

Parenthesizing arguments it's always a good practice to avoid side-effects on expansion.

查看更多
冷血范
7楼-- · 2020-05-11 10:16

This one is awesome:

#define NEW(type, n) ( (type *) malloc(1 + (n) * sizeof(type)) )

And I use it like:

object = NEW(object_type, 1);
查看更多
登录 后发表回答