C code that print its own source

Very interesting. The trick is that use s to print itself, thus s should not contain any character like “\n”, “\”” which will be displayed differently as its literal value. Thus, we use numbers to represent those special characters.
[sourcecode language=”cpp”]
#include <stdio.h>
int main(){const char *s="#include<stdio.h>%cint main(){const char *s=%c%s%c;printf(s,10,34,s,34);}";printf(s,10,34,s,34);}
[/sourcecode]

2 thoughts on “C code that print its own source”

    1. Your Java version is smart.
      It is also possible to use variables names like s1,s2,s3 instead of part of existing strings (“s2″ can be generated by s5+2 where s5=”s”):

      class A {public static void main(String[] args) {String s1=”class A {public static void main(String[] args) {String s1=”,s2=”\””,s3=”\\”,s4=”,”,s5=”s”,s6=”=”,s7=”;System.out.println(s1+s2+s1+s2+s4+s5+2+s6+s2+s3+s2+s2+s4+s5+3+s6+s2+s3+s3+s2+s4+s5+4+s6+s2+s4+s2+s4+s5+5+s6+s2+s5+s2+s4+s5+6+s6+s2+s6+s2+s4+s5+7+s6+s2+s7+s2+s7);}}”;System.out.println(s1+s2+s1+s2+s4+s5+2+s6+s2+s3+s2+s2+s4+s5+3+s6+s2+s3+s3+s2+s4+s5+4+s6+s2+s4+s2+s4+s5+5+s6+s2+s5+s2+s4+s5+6+s6+s2+s6+s2+s4+s5+7+s6+s2+s7+s2+s7);}}

Leave a Reply

Your email address will not be published. Required fields are marked *