This classic ioccc entry is a Hello World program written in C. Can anyone please provide an explanation of how it works?
Original code (syntax highlighting intentionally missing):
int i;main(){for(;i["]<i;++i){--i;}"];read('-'-'-',i+++"hell\
o, world!\n",'/'/'/'));}read(j,i,p){write(j/p+p,i---j,i/i);}
Slightly cleaner:
int i;
main()
{
for ( ; i["]<i;++i){--i;}"]; read('-' - '-', i++ + "hello, world!\n", '/' / '/'));
}
read(j, i, p)
{
write(j / p + p, i-- - j, i / i);
}
for loop condition
This expression takes advantage of the fact that array indexing is commutative in C. It is equivalent to.
So the loop will terminate when the character at position
iis\0, i.e., at the end of the string, which is 14 characters long (which happens to be the same length as “hello, world!\n”). So theforloop condition can be rewritten as:character arithmetic
charis an integer type, and thus:'-' - '-'is 0'/' / '/'is 1read(0, i++ + “hello, world!\n”, 1)
After fixing all the compiler warnings (like implicit int to pointer conversion), and simplifying the things mentioned above, the code becomes:
(I renamed
readtoread2to avoid conflicting with the Unixreadfunction.)Note that the
jandparguments toread2are unneeded, as the function is always called with j=0 and p=1.The call
write(1, i--, 1)writes 1 character fromito file descriptor 1 (stdout). And the postdecrement is superfluous because thisiis a local variable never referenced again. So this function is equivalent toputchar(*i).Inlining the
read2function within the main loop givesfor which the meaning is obvious.