Path: utzoo!mnetor!uunet!husc6!hao!oddjob!gargoyle!ihnp4!cbosgd!gwspc!cbcsta!n8emr!oink!jep
From: jep@oink.UUCP (James E. Prior)
Newsgroups: comp.lang.c
Subject: Creme de la Creme of UGLY CODE
Message-ID: <209@oink.UUCP>
Date: 12 Dec 87 16:07:16 GMT
Reply-To: jep@oink.UUCP (James E. Prior)
Organization: Random Prime Research Institute  Columbus, Ohio
Lines: 48

Recently someone posted a piece of ugly code, which many
people revelled in commenting on.  Dey ain't seen nut'in!

Don Libes of Micro/Systems Journal holds an annual
International Obfuscated C Code Contest.  I've seen
some real gems from it the last couple of years.

My all time favorite piece of bad code was in 1986 from 
Lennart Augustsson (seismo!mcvax!enea!chalmers!augustss)
is as follows:

#define p struct c
#define q struct b
#define h a->a
#define i a->b
#define e i->c
#define o a=(*b->a)(b->b,b->c)
#define s return a;}q*
#define n (d,b)p*b;{q*a;p*c;
#define z(t)(t*)malloc(sizeof(t))
q{int a;p{q*(*a)();int b;p*c;}*b;};q*u n a=z(q);h=d;i=z(p);i->a=u;i->b=d+1;s
v n c=b;do o,b=i;while(!(h%d));i=c;i->a=v;i->b=d;e=b;s
w n o;c=i;i=b;i->a=w;e=z(p);e->a=v;e->b=h;e->c=c;s
t n for(;;)o,main(-h),b=i;}main(b){p*a;if(b>0)a=z(p),h=w,a->c=z(p),a->c->a=u,a->c->b=2,t(0,a);putchar(b?main(b/2),-b%2+'0':10);}

Don Libes's comments: This is really obscure.  I recommend running this
first, then renaming the functions more descriptively.

My own comments.  This program has several levels of obfuscation.  Most
obfuscation attempts are just the inverse of cb.  That is, they use many
misleading #defines, and cram it on a few lines.  L.A.'s gem goes far
beyond that.  Once you have run the code through cpp and cb, you have
a program that looks almost simple.  That's the most beatiful part of
L.A.'s obfuscation: It looks simple, but it isn't.  The function calling
sequence is quite ingenius.  

Some newer compilers either crash or get confused about the meaning of
certain identifiers.  There *is* enough information from the context 
in which they are used, to properly derive the proper meaning.  I've
seen some compilers compile it as is.  If your compiler can't derive 
the proper meaning of all the identifiers, then you'll have to change 
some of them.  Be careful if you do.

You can learn much about the C language from this and other obfuscated
programs.

-- 
Jim Prior    jep@oink.UUCP    {ihnp4|cbosgd}!n8emr!oink!jep