4 ms·
I was going to make a snarky comment to the effect that the Rust syntax for an array of pointers to functions isn't obviously less weird than the C syntax -- I
by gjm11 7y ago
I was going to make a snarky comment to the effect that the Rust syntax for an array of pointers to functions isn't obviously less weird than the C syntax -- I assume the basic thing there is [<type>; <size>] -- but then I noticed that the C syntax above was very wrong, and the correct syntax is weirder :-).
So what it should actually be is int ( * [4])(). The principle is that "declaration mimics use" and that a type is written like a declaration with the variable name omitted. So, for an array of pointers to functions mapping no-args to int:
If f is such a function, you would call it as f() and get an int, so the declaration would look like int f() and the type would be int () except that functions, as opposed to function pointers, aren't first-class objects in C and don't have a type.
If pf is a pointer to such a function, you would need ( * pf) instead of f, so the declaration would be int ( * pf)() and the type would be int ( * )().
If apf is an array of those, then you would need to replace pf with apf[something], so the declaration would be int ( * apf[4])() and the type would be int ( * [4])().
Which is, indeed, a bit weird.
(Note: Spaces around all the asterisks because that seems to be the least-bad way of making HN not interpret them as markup. It's quite impressive how damaging HN's markup feature manages to be given how little it's capable of.)
- jcranmer 7y agoGood lord, you're right. I constructed the C syntax off the top of my head, and I knew about the declaration-mimics-use, so I started constructing it as if I would use it... I just somehow mixed up the [4] and the (). C's function pointer and array syntax does make sense when you understand it, but even for experts, it can be difficult to get it right on the first go.