A Quine in C
A Quine is a program that copies itself.
That is, if you run a quine, you get another program, which is also a quine. The same quine as before. So if you run this new one again, you have another quine. And so on, and so on. In technical language we'd say that the output of a quine is it's own source code. If we were really pretentious we'd say that a quine represents a fixed point in a programming environment. Try using that one at a party, I bet the ladies will love it.
There is an obvious diabolical application of this property: namely, worms and viruses. But just because a program has this property doesn't mean it's malicious code. It's fun to write a quine, and enlightening. I wrote one in C.
C is not the ideal language for this. Interpreted languages, like Python or LISP, are much better for it. C can still do it, though, and the extra headaches of doing it in C may help one understand better what is involved.
How to do it?
If you're like me, you immediately think: "Hey, this is easy! just write a program that reads it's own source code and copies it to a new file!". While such a solution is easy and seems to meet the criteria, there is a problem with it: You have no guarantee that your source code will be available to read from. The real trick to a quine is embedding your source code in your executable code.
Our first quine, the simplest possible I could imagine, requires only that it prints out a program that, when compiled, prints out a program, etc. etc. Really, we just need the bare include statement, main, printf, and return 0. Then, what we put into printf needs to itself be equal to that same series of statements. Here's a first go at it:
Clearly, this is not a quine. This is a program that produces a program that prints "Hello, World!", ("Hello, World!" is not a program, for those of you who might be wondering). We are up against one of the programmer's most nefarious enemies, the infinite regress. You see the problem. Within printf(), I must put the source code, which has a printf(), in which I must put the source code, and so on, and so on.
The infinite regress, of course, can only be defeated by using a suitable base case. What was the base case? I figured it must be the literal program text. So then, the recursive case must be the quoted program text (the text to print). I needed only to be able to distinguish these two and yet keep them together when the program ran.
My moment of genius (I do have those moments, despite what you might think) came when I realized this, and how I could do it. I simply had to separate the source code into a quoted string, named as a variable, and then print that quoted string 'as-is', embedded in that same quoted string, 'unquoted'. Here's the result: