2011年1月11日 星期二

A program that prints itself

#include <stdio.h>
#include <assert.h>
int main(void)
{
  FILE *fp;
  int c;
  fp = fopen(__FILE__, "r");
  assert(fp != NULL);
  while ((c = fgetc(fp)) != EOF)
    putchar(c);
  fclose(fp);
  return 0;
}

2 則留言:

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

    :p

    回覆刪除
  2. This is called a "quine" and it's covered in the book "Gödel, Escher, Bach: An Eternal Golden Braid" (luckily I have one copy of it :)) It is basically derived from the paradox-producing expression which is known as Quine Paradox:

    "Yields falsehood when preceded by its quotation" yields falsehood when preceded by its quotation.

    http://en.wikipedia.org/wiki/Quine_%28computing%29

    回覆刪除