今天在工作中我们遇到了以下代码(你们中的一些人可能认识到它):
#define GET_VAL( val, type ) \ { \ ASSERT( ( pIP + sizeof(type) ) <= pMethodEnd ); \ val = ( *((type *&)(pIP))++ ); \ }
基本上我们有一个字节数组和一个指针.宏返回对类型变量的引用,并将指针前进到该变量的末尾.
它让我想起了几次我需要"像解析器一样思考"才能理解C++代码.
您是否知道其他代码示例导致您多次停止并阅读它,直到您设法掌握它的假设?
Quake 3中的反平方根实现:
float InvSqrt (float x){ float xhalf = 0.5f*x; int i = *(int*)&x; i = 0x5f3759df - (i>>1); x = *(float*)&i; x = x*(1.5f - xhalf*x*x); return x; }
更新: 这是如何工作的(感谢ryan_s)
这是最近的reddit http://www.eelis.net/C++/analogliterals.xhtml
assert((o-----o | ! ! ! ! ! ! ! o-----o ).area == ( o---------o | ! ! ! o---------o ).area );
Duff的设备(http://en.wikipedia.org/wiki/Duff%27s_device)让我做恶梦:
strcpy(to, from, count) char *to, *from; int count; { int n = (count + 7) / 8; switch (count % 8) { case 0: do { *to = *from++; case 7: *to = *from++; case 6: *to = *from++; case 5: *to = *from++; case 4: *to = *from++; case 3: *to = *from++; case 2: *to = *from++; case 1: *to = *from++; } while (--n > 0); } }
我知道它是C而不是C++,但总是有国际混淆的C代码竞赛.我在那里看到了一些会让你头晕目眩的代码.
unsigned int reverse(register unsigned int x) { x = (((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1)); x = (((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2)); x = (((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4)); x = (((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8)); return((x >> 16) | (x << 16)); }
反转int中位的顺序.
这是众所周知但仍然令人印象深刻的方式来交换两个整数而不创建临时变量:
// a^=b^=a^=b; // int a and int b will be swapped // Technically undefined behavior as variable may only // be assined once within the same statement. // // But this can be written correctly like this. // Which still looks cool and unreadable ;-) a^=b; b^=a; a^=b;
大多数Boost的东西 - 模板元编程很糟糕,但是当你考虑到让它在某些编译器(*coughborlandcough*)上工作所必需的变通方法时,它就变得非常荒谬了.试着去了解Boost.Bind.试一试.