I hope you enjoyed crafting your solution for this month’s Exercise. It’s just for fun, as I assume no one is going to mess with C to such a degree that their code becomes so completely unrecognizable. Still, C coders are a mischievous bunch.
Here is the way the mystery code is presented:
begin program start print("Hello!") end stop
To me, this code looks like a programming language from the early days of computing, back in the mainframe days. This notion was my inspiration. To write the faux code, I replaced parts of C code I’d already written one step at a time. Here is the original program:
#include <stdio.h> int main() { puts("Hello!"); return(0); }
Starting with Line 3, I replaced each element with a defined constant. The first line required two of them, as I didn’t want to mess with the space between int and main():
#define begin int
#define program main()
So the word begin
is replaced with the keyword int throughout the code, and program
becomes main(). This trick works for such a short program, but for longer code it would present lotsa problems.
The left brace is replaced with start
:
#define start {
To substitute the puts() function I defined the print()
macro. Argument a
is used in both:
#define print(a) puts(a);
See how the semicolon is added above? It allows me to use print()
without the semicolon, which adds to the faux code’s mystery.
The last two #defines
complete the process:
#define end return(0);
#define stop }
Here is the complete code:
2021_05-Exercise.c
#include <stdio.h> #define begin int #define program main() #define start { #define print(a) puts(a); #define end return(0); #define stop } begin program start print("Hello!") end stop
I hope you had fun coming up with a similar solution. You can use #define
to change the way the compiler reads C code, though I recommend not getting carried away. The true purpose of defining something new should be to make the code more readable or elegant. But nothing requires that C programmers use these same tools to be devious.
The begin/end reminded me of Pascal, and made me wonder whether it would be theoretically possible to fully implement another language like this. It would actually make sense to do so if possible.
I have a very old C manual that did just that. It was my inspiration.