3 ms·
Yay, yet another post on HN about mental clutches people use to read C declarations. It helps a bit browsing through the source code of some of the first C com
by st_goliath 6y ago
Yay, yet another post on HN about mental clutches people use to read C declarations.
It helps a bit browsing through the source code of some of the first C compilers. The Unix Heritage Society[1] hosts source tar balls for very old Unixen, including the first C compilers.
One of the other posts in this thread ("Declaration matches usage.") is pretty close. Basically they originally [ab]used part of the expression parser plus some hacks on top to parse declarations, i.e. something like parsing <type> <expr> ';' and then assigning <type> to the root node and pushing it downwards through the tree to derive the type for the free variables at the leaves.
That's why
int *a, b;
makes `a` a pointer, but not `b` (and why it's written that way). The int type is assigned to the root node (the `,` operator which has lowest precedence), then pushed to the nodes attached to it. Thus, `b` is derived to be of type `int` as well as ` * a`, which in the next step determines `a` to be of type `pointer-to-int`.
I recall reading a quote from Dennis Ritchie somewhere that the `( * name)` syntax for function pointers was required to "guide the parser" (read: hacks on top), but can't seem to find it right now.
Note that this was all before ANSI times. The current declaration rules have of course been derived and extended
from there, but it helps a little understanding some of the oddities.
But even when reading through the C syntax in the first ANSI standard, you might realise that most of the expressiveness in C actually comes from, well it's expression syntax, and you can still shoehorn most of the declaration syntax in there as well, covering probably most of the language syntax using just the expression parser. (Which helps if you are in the 70ies, writing a compiler on a PDP-11 for your little toy OS, unaware that you are building the foundations for lots of things to come after)
[1] https://www.tuhs.org/ https://www.tuhs.org/