问题描述
例如,最近我碰到这个排在linux内核:
For example, I recently came across this in the linux kernel:
/* Force a compilation error if condition is true */
#define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))
所以,在你的code,如果你有一些结构必须是,说的8个字节大小,因为也许有些硬件限制的倍数,你可以这样做:
So, in your code, if you have some structure which must be, say a multiple of 8 bytes in size, maybe because of some hardware constraints, you can do:
BUILD_BUG_ON((sizeof(struct mystruct) % 8) != 0);
和它不会编译除非结构MYSTRUCT的大小是8的倍数,如果是8的倍数,在所有生成的任何运行时code。
and it won't compile unless the size of struct mystruct is a multiple of 8, and if it is a multiple of 8, no runtime code is generated at all.
我知道另一个技巧是从书图形宝石,而在其他模块使用该模块,可让一个头文件既声明和初始化变量在一个模块中,仅仅声明为实习医生。
Another trick I know is from the book "Graphics Gems" which allows a single header file to both declare and initialize variables in one module while in other modules using that module, merely declare them as externs.
#ifdef DEFINE_MYHEADER_GLOBALS
#define GLOBAL
#define INIT(x, y) (x) = (y)
#else
#define GLOBAL extern
#define INIT(x, y)
#endif
GLOBAL int INIT(x, 0);
GLOBAL int somefunc(int a, int b);
通过如此,code定义X和somefunc所做的:
With that, the code which defines x and somefunc does:
#define DEFINE_MYHEADER_GLOBALS
#include "the_above_header_file.h"
而仅仅是使用X和somefunc()做code:
while code that's merely using x and somefunc() does:
#include "the_above_header_file.h"
所以,你得到一个声明,他们需要全局和函数原型的两个实例一个头文件,以及相应的外部声明。
So you get one header file that declares both instances of globals and function prototypes where they are needed, and the corresponding extern declarations.
那么,什么是你最喜欢的C编程技巧沿着这些线路?
So, what are your favorite C programming tricks along those lines?
推荐答案
C99使用匿名数组提供了一些非常酷的东西:
C99 offers some really cool stuff using anonymous arrays:
删除无意义的变量
{
int yes=1;
setsockopt(yourSocket, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
}
变为
setsockopt(yourSocket, SOL_SOCKET, SO_REUSEADDR, (int[]){1}, sizeof(int));
传递参数数量可变
void func(type* values) {
while(*values) {
x = *values++;
/* do whatever with x */
}
}
func((type[]){val1,val2,val3,val4,0});
静态链表
int main() {
struct llist { int a; struct llist* next;};
#define cons(x,y) (struct llist[]){{x,y}}
struct llist *list=cons(1, cons(2, cons(3, cons(4, NULL))));
struct llist *p = list;
while(p != 0) {
printf("%d\n", p->a);
p = p->next;
}
}
任何我我都没有想到的肯定有很多其他很酷的技巧。
Any I'm sure many other cool techniques I haven't thought of.
这篇关于什么是你最喜欢的C编程把戏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!