Monday, July 9, 2012

Evil C


This is a collection of strange C (and some Java) constructs. It's probably best not to use them, but you should know why they work
.

The cast-to-bool operator

Node *left, *right;
int childCount() 

{
return !!left + !!right;
}


Logical XOR
A variation on the above. (Note that ^ is bitwise XOR, not logical XOR; 3 ^ 4 does not give 0.)

int xor(int a, int b)
{
return !a != !b;
}



The "goes toward" operator

void doStuff(int count)

{
while(count --> 0)
fleh();
}


Useless but pretty definitions of BOOLs

#define TRUE '/'/'/'
#define FALSE '-'-'-'
Two (2) readers wrote in to comment that the above is unsafe due to operator precedence.
Yes.
That is true.
If you are doing arithmetic with the above, please seek help.

Optimization, the Microsoft way

This was found in the 2004 leaked Windows sources

__inline BOOL
SearchOneDirectory(
IN LPSTR Directory,
IN LPSTR FileToFind,
IN LPSTR SourceFullName,
IN LPSTR SourceFilePart,
OUT PBOOL FoundInTree
)
{
//
// This was way too slow. Just say we didn't find the file.
//
*FoundInTree = FALSE;
return(TRUE);
}


The canonical temp-less swap

As about a dozen people have reminded me over the last 24 hours, and as this page used to say, this is not well-defined nowadays.
a^=b^=a^=b;

Duff's Device for loop unrolling
switch(c&3) while((c-=4)>=0)

{
foo(); case 3:
foo(); case 2:
foo(); case 1:
foo(); case 0:
}



Struct/class offsets

int ofs = (int)&((Class*)0)->element;
[Vilhelm S. comments: Note that <stddef.h> provides an offsetof(type, field_name) macro, so you can leave the dirty work of abusing NULL pointers in perverted ways to your standard library implementor! (The typical implementation of it is as above, though...)]


Fun with comments

This font definition has a bug. Find it.

char font[] = {
....
0x00,0x61,0x51,0x49,0x45,0x43,0x00,0x00, // 1 :0x5A Z
0x70,0x29,0x24,0x22,0x24,0x29,0x70,0x00, // 1 :0x5B [
0x00,0x3D,0x42,0x42,0x42,0x42,0x3D,0x00, // 1 :0x5C \
0x00,0x3C,0x41,0x40,0x41,0x40,0x3C,0x00, // 1 :0x5D ]
...


[Bernd Jendrissek writes: OMG I can't believe you stole code from my ex-job! I actually bumped into the font definition problem... except that two compilers behaved differently! TopSpeed C and GCC, in particular. The former didn't respect the backslash as a line continuation of a comment, so the code worked. Can't blame it too much, I think that compiler predates C99.]


Endian magic

This is just plain evil.

// this is from GMP
#define BYTE_OFS(x) (((char *)&internalEndianMagic)[7-(x)])
static double internalEndianMagic = 7.949928895127363e-275;


Yes, it works by exploiting the exact IEEE binary representation of that constant.
2008-09-04: According to Moritz Both the the Borland compiler gets the constant wrong.. Ouch.

Another micro-optimization

"If x or y is less than 0" :-) Works with and and xor as well

if((x|y) < 0) { ... }
[Benoit Hudson comments: Thankfully, gcc -- usually the lowest common denominator among compilers -- implements this optimization. So it's all right to beat your minion programmers with a stick when they do this by hand.]
Lispy with-foo-bound-to

#define within(obj) for(QWidget *__t = (obj), *parent = __t; parent; parent=0)
within(this) {
within(new QSplitter(parent)) {
within(new QVBoxWidget(parent)) {
...
...
}
within(...) {
...


Dan's lexer tester

/* Test whether compiler supports C++-style comments */
#define HELPER 0//**/
#define CPLUSPLUS_COMMENTS_SUPPORTED (HELPER+1)
[] is symmetric
thanks sigfpe
int direction = 1;
char direction_name = direction["nsew"];


Walsh-Moler-Newton inverse square root
Thanks captainfwiffo, gsg and Anders; this one is actually useful (and thus shouldn't really be on this page) but makes up for it by pure IEEE abuse. History here.

float Q_rsqrt( float number )
{
long i;
float x2, y;
const float threehalfs = 1.5F;
x2 = number * 0.5F;
y = number;
i = * ( long * ) &y; // grab bits
i = 0x5f3759df - ( i >> 1 ); // do magic
y = * ( float * ) &i;
y = y * ( threehalfs - ( x2 * y * y ) ); // improve
return y * number;
}

snoob

This one is for mrkite. Given an integer with n bits set, it will return the next higher number with the same number of bits set. From Hacker's Delight.

unsigned snoob(unsigned x) {
unsigned smallest, ripple, ones;
// x = xxx0 1111 0000
smallest = x & -x; // 0000 0001 0000
ripple = x + smallest; // xxx1 0000 0000
ones = x ^ ripple; // 0001 1111 0000
ones = (ones >> 2)/smallest; // 0000 0000 0111
return ripple | ones; // xxx1 0000 0111
}



List comprehensions, Java style

return new ArrayList<String>() {{ for(String x : foo) add(x.toUpper(); }};
These are something we are not suppose to do so, but a virus will!!! LOL..! But we should know why and how these works!!

No comments:

Post a Comment