Printf-Tac-Toe
93 points by carlos-menezes 5 days ago | 8 comments

JKCalhoun 4 hours ago
Contestant: "I'll take My Dirty Programming Secrets for 100, Alex."

Alex: "Its primary purpose is to serve as The One True Debugger."

(It has certainly served me well.)

reply
binaryturtle 2 hours ago
That's the content why I check HN! :)
reply
idorozin 6 hours ago
This is both impressive and slightly terrifying. Format strings are way more powerful than most people realize.
reply
LoganDark 2 hours ago
To be fair, this is actually `scanf` and `printf` in a loop. The `scanf` is buried in the `arg` define.
reply
danbruc 7 hours ago
How did we end up with printf - within a loop - being Turing-complete? Was it designed that way from the beginning? Were new features added over time until we got there?
reply
marmakoide 7 hours ago
Having something Turing-complete is surprisingly easy, and it hides everywhere. The repository have a small document that explains how you can use printf() as a computer : it can performs additions, logical union and negation, which is enough.

It was unintentional, but Ken Thompson being Ken Thompson, can't be 100% sure.

reply
danbruc 6 hours ago
So there was no extension of the functionality over time, all the formats have been supported from day one?
reply
st_goliath 5 hours ago
The key features that is used here is the '%n' format specifier, that fetches a pointer as the next argument, and writes a character count back.

There is actually an interesting question here: was '%n' always in printf, or was it added at one point?

I took a cursory look at some old Unix source archives at TUHS: https://www.tuhs.org/cgi-bin/utree.pl

As far as I can tell from the PDP-11 assembly, Version 7 research Unix (relevant file: /usr/src/libc/stdio/doprnt.s) does not appear to implement it.

The 4.1BSD version of that file even explicitly throws an error, treating it as an invalid format specifier.

The implementation in a System III archive looks suspiciously similar to the BSD one, also throwing an error.

Only in a System V R4 archive (relevant file: svr4/ucblib/libc/port/stdio/doprnt.c) I found an implementation of "%n" that works as expected.

I guess it was added at some point to System V and through that eventually made it into POSIX?

reply