Avatar of evilrix
Flag for United Kingdom of Great Britain and Northern Ireland

asked on 

Write a program to output it's own source code using ANSI C/C++ (puzzle for experts)

This isn't really a question; rather, it is a puzzle!!!

Please note, this is NOT an assignment of any kind (check my profile if you are unsure as to my tenure on the site). The idea is to spark some activity in the C/C++ topic areas and to have a little fun. Points will be awarded to the expert(s) who provide the most interesting solution. The idea is to have a little fun, promote discussion and have something interesting to think/talk about.

If this goes well, I plan on doing one of these types of puzzle questions on a regular(ish) basis. I would like to see expert colaboration, rather than experts just going gun-ho to get points. I will consider colaboration between experts when I finally award points. I will close this question once I believe it has reached a natural conclusion (ie. no futher productive activity).

So, let's start with the first puzzle. It's one that has been set many times before and I'd be interested in seeing different approaches to solving it. Please don't just search Google and copy/paste. I promise I will check and any plaigirised answers will be ignored (and probably deleted).

Let's go...

Your job is to write a program that, when run, outputs it's own source code (including comments) such that if the output was fed back into a compiler, built and run it would do exactly the same thing as the original program. The output must be word for word identical to the original source code, such that performing a diff between the original source code and the output would show zero differences.

You may use any feature of the latest C/C++ standards, but you must NOT use any 3rd party libraries or Operating System specific code. Basically, your code needs to be 100% ANSI standard and should build, run and behave correctly using any standards complient compiler (gcc, clang, Visual Studio [*cough*]). You must NOT use embedded assembly nor may you use any compiler tricks that the ANSI standards state would be undefined or unspecified behaviour.

Ideally, I would like to see the full source code posted in the comment along with a link to your working solution using the https://ideone.com/ online compiler. You may use either C or C++ as long as your code is standards complient, with the very latest standards for C/C++.

I look forward to seeing your submissions.

EE Topic Advisor

Avatar of undefined
Last Comment

8/22/2022 - Mon