C – Interview Hello World Explanation with Obfuscation

c++obfuscation

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);
}

Best Answer

for loop condition

i["]<i;++i){--i;}"]

This expression takes advantage of the fact that array indexing is commutative in C. It is equivalent to.

"]<i;++i){--i;}"[i]

So the loop will terminate when the character at position i is \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 the for loop condition can be rewritten as:

i != 14

character arithmetic

read('-' - '-', i++ + "hello, world!\n", '/' / '/')

char is an integer type, and thus:

  • '-' - '-' is 0
  • '/' / '/' is 1

    read(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:

#include <unistd.h>

int i = 0;

void read2(int, char*, int);

int main()
{
   while (i != 14)
   {
      read2(0, i++ + "hello, world!\n", 1);
   }

   return 0;
}

void read2(int j, char* i, int p)
{
   write(j / p + p, i-- - j, 1);
}

(I renamed read to read2 to avoid conflicting with the Unix read function.)

Note that the j and p arguments to read2 are unneeded, as the function is always called with j=0 and p=1.

#include <unistd.h>

int i = 0;

void read2(char*);

int main()
{
   while (i != 14)
   {
      read2(i++ + "hello, world!\n");
   }

   return 0;
}

void read2(char* i)
{
   write(1, i--, 1);
}

The call write(1, i--, 1) writes 1 character from i to file descriptor 1 (stdout). And the postdecrement is superfluous because this i is a local variable never referenced again. So this function is equivalent to putchar(*i).

Inlining the read2 function within the main loop gives

#include <stdio.h>

int i = 0;

int main()
{
   while (i != 14)
   {
      putchar(*(i++ + "hello, world!\n"));
   }

   return 0;
}

for which the meaning is obvious.

Related Question