Self-printing C program

Torben [gidius Mogensen torbenm at gere.diku.dk
Mon Sep 17 23:46:44 AEST 1990


meyer at unix.cis.pitt.edu (Timothy S. Meyer) writes:


>Seems to me I saw a self-printing C program a few years back in CACM or
>Computer magazine, but I can't seem to find it.  Can anyone give me a
>reference for such a program?  (A self-printing program is one that 
>outputs a copy of its own text and is more of a recreational interest I
>think.)

>Any help will be appreciated.

I have several versions: one assume a maximum linelength of 80, the
other is a single long line.

------------------ max 80 ---------------------
char *a="\n\\\"char *a=%c%cn%c%c%s%c,*b=%.1s%c%s%c;%.1s%s%.1s",*b=
"main(){printf(a+3,a[2],a[1],a[1],a[1],a+1,a[2],a,a[2],b,a[2],a,b,a);}";
main(){printf(a+3,a[2],a[1],a[1],a[1],a+1,a[2],a,a[2],b,a[2],a,b,a);}
------------------ 1 line ---------------------
char *a="\\\"char *a=%c%.1s%.1s%.71s%.1sn%c;main(){printf(a+2,a[1],a,a,a,a,a[1]);}\n";main(){printf(a+2,a[1],a,a,a,a,a[1]);}
-----------------------------------------------

I also have Pascal programs:

------------------ max 80 ---------------------
program s(output);const a='program s(output);const a';b
=''';begin writeln(a,p,a,b:3);writeln(p,b:1,b,b:2);writeln(a:1,p,p,b:1,b)end.';
p='=''';begin writeln(a,p,a,b:3);writeln(p,b:1,b,b:2);writeln(a:1,p,p,b:1,b)end.
------------------ 1 line ---------------------
program s(output);const a=''';begin writeln(be,b,a:1,a,a:4,b,be,a:3,b,b,a:1,a)end.';be='program s(output);const a';b='=''';begin writeln(be,b,a:1,a,a:4,b,be,a:3,b,b,a:1,a)end.
-----------------------------------------------

You can make these shorter by omitting (output) in the heading, but
that will cause warnings when compiled.


Torben Mogensen (torbenm at diku.dk)



More information about the Comp.lang.c mailing list