A new "Hello, World!" for C
Most of us have a good idea how to write a simple “Hello, World!” program in C, but sometimes it feels a little too easy. Luckily, we can always make it more of a challenge!
Consider a hypothetical situation where many symbols are banned, such as "
, '
, \
, #
, {
, and }
, and we aren’t allowed the string Hello, World!
as a subsequence in the code. How would we write a “Hello, World!” program then?
Is it impossible, because we can no longer use {}
to write a block of code for a function? Is it impossible, because we can’t actually embed the string?
Well, it is possible! Here’s a possible solution:
We are invoking some C features from the ancient times, and also some less known features.
The first order of magic is digraph and trigraphs, which are two or three letter sequences used to represent some characters that were not available on all the machines back in the early days of C. For example, here we are using %:
and ??=
for #
, <%
for {
, ??>
for }
, and ??/
for \
. For more details, see Wikipedia.
This enough is not able to avoid quotes. We now invoke a C macro feature, the #
sign (or %:
in this example). When using #
in front of a macro argument, the macro argument will be replaced by its string representation.
Here, we define the putz(x)
macro as puts(#x)
, which means putz(Hello, World!)
will be converted into puts("Hello, World!")
.
Now, this alone is not enough to bypass the rule against having Hello, World!
as a subsequence in the code. Fortunately, this is easy to avoid with some escapes.
We use a mixture of octal escapes, which are \
followed by up to three octal digits, and hexadecimal escapes, which are \x
followed by two hexadecimal digits, representing the ASCII value of the character. For the gory details, see Wikipedia.
Using these features together allows us to craft the above program, solving this fun challenge.