Program The rantings of a lunatic Scientist

Posts tagged as C

A Quine in C

C/C++ Daily Programmer

Another reddit /r/Daily Programmer challenge.

Write a Quine.

I first read about quines several years ago but have never gotten around to trying to write one. I decided to write it in my language of choice, C/C++, and more specifically C to keep it as simple as possible. The code could be shorter, in fact I’ve seen one liner Quines written in C. But I wanted to keep proper formatting and commenting and to have this formatting persist in the result of running it.

The Quine works by creating a C-String with the initial scaffolding of the program. However, where the redefinition of this inner string would occur we instead use the string formatting phrase %s which tells the printf function to insert the value of another C-String in it’s place. By doing so we can then pass our string s to printf twice, once as the string format, and a second time as the value for injection where the %s flag is. We also use the same trick with the %c flag which injects a single character to inject the hex-values of the new-line character \n or 0x0a and the quote character \" or 0x22. By using the hex-values instead of the escaped literals we don’t have to worry about escaping the inner string while printing to stop the backslashes from being evaluated.