Search code examples
cquine

How does this program duplicate itself?


This code is from Hacker's Delight. It says this is the shortest such program in C and is 64 characters in length, but I don't understand it:

    main(a){printf(a,34,a="main(a){printf(a,34,a=%c%s%c,34);}",34);}

I tried to compile it. It compiles with 3 warnings and no error.


Solution

  • This program relies upon the assumptions that

    • return type of main is int
    • function's parameter type is int by default and
    • the argument a="main(a){printf(a,34,a=%c%s%c,34);}" will be evaluated first.

    It will invoke undefined behavior. Order of evaluation of arguments of a function is not guaranteed in C.
    Albeit, this program works as follows:

    The assignment expression a="main(a){printf(a,34,a=%c%s%c,34);}" will assign the string "main(a){printf(a,34,a=%c%s%c,34);}" to a and the value of the assignment expression would be "main(a){printf(a,34,a=%c%s%c,34);}" too as per C standard --C11: 6.5.16

    An assignment operator stores a value in the object designated by the left operand. An assignment expression has the value of the left operand after the assignment [...]

    Taking in mind the above semantic of assignment operator the program will be expanded as

     main(a){
          printf("main(a){printf(a,34,a=%c%s%c,34);}",34,a="main(a){printf(a,34,a=%c%s%c,34);}",34);
    }  
    

    ASCII 34 is ". Specifiers and its corresponding arguments:

    %c ---> 34 
    %s ---> "main(a){printf(a,34,a=%c%s%c,34);}" 
    %c ---> 34  
    

    A better version would be

    main(a){a="main(a){a=%c%s%c;printf(a,34,a,34);}";printf(a,34,a,34);}  
    

    It is 4 character longer but at least follows K&R C.