Good code is a work of art

Nov 28, 2005 01:41


I read two instances of beautiful (or clever) C code on comp.lang.c over the past few days. Livejournal seems like a good place to make a "bookmark" for them, and tell others about it.

First, a C palindrome:

/**/char q='"',*a="*//**/char q='%c',*a=%c%s%c*/};)]d-062[b=]d[b( rahctup)--d(elihw;)q,a,q,q,2+a,b(ftnirps{)(niam;162=d tni;]162[b," ,b[261];int d=261;main(){sprintf(b,a+2,q,q,a,q);while(d--) putchar(b[d]=b[260-d]);}/*c%s%c%=a*,'c%'=q rahc/**//*"=a*,'"'=q rahc/**/

(Join the lines to make it single-line C code). Compiling and running the program is fun.

Then, something more complicated and useful: you have several constants in a C program and you want to make sure that all of them are smaller than a given other constant.

Here is one of the solutions offered in the thread. You will need to read the complete message to understand what's going on (or you could figure it out yourself).
So if you have for example ten constants c0, c1, ..., 9 and you want to check at compile time that each is less than 10, then all you need to do is to write a function

static void compiletimechecks (void) { sizeof ("" == ! (c0 < 10)); sizeof ("" == ! (c1 < 10)); ... sizeof ("" == ! (c9 < 10)); }

This is "smart". Another solution offered in the same thread reads:

#define DEF_CHECKED_VAL(name, value) \ enum { name = (value) < MAX ? (value) : MAX };

This is elegant. As is almost always the case, elegant wins over smart.
Previous post Next post
Up