←back to thread

35 points bluetomcat | 3 comments | | HN request time: 0s | source

A small tool that parses C declarations and outputs a simple visual representation at each stage, as it encounters arrays, pointers or functions.

The program uses a table-driven lexer and a hand-written, shift-reduce parser. No external dependencies apart from the standard library.

Show context
pcfwik ◴[] No.46187443[source]
Since this is about C declarations: for anyone who (like me) had the misfortune of learning the so-called "spiral rule" in college rather than being taught how declarations in C work, below are some links that explain the "declaration follows use" idea that (AFAIK) is the true philosophy behind C declaration syntax (and significantly easier to remember/read/write).

TL;DR: you declare a variable in C _in exactly the same way you would use it:_ if you know how to use a variable, then you know how to read and write a declaration for it.

https://eigenstate.org/notes/c-decl https://news.ycombinator.com/item?id=12775966

replies(2): >>46188202 #>>46189393 #
nitrix ◴[] No.46188202[source]
That is correct.

  int x, *p, arr[5], fn(), (*pfn)();
Using x, or dereferencing p, or subscripting the array arr, or declaring a function that can be called with fn, or dereferencing the function pointer pfn then calling it, all these things would produce an int.

It's the intended way to read/write declarations/expressions. As a consequence, asterisks ends up placed near the identifiers. The confused ones will think it's a stylistic choice and won't understand any of this.

replies(3): >>46188242 #>>46188970 #>>46189272 #
saagarjha ◴[] No.46188242[source]
Of course, the correct way to use a function pointer is to call it.
replies(1): >>46188249 #
1. nitrix ◴[] No.46188249{3}[source]
Yes, the () operator dereference function pointers automatically for you for convenience. There's also the surprise that you can infinitely dereference function pointers as they just yield you more function pointers.
replies(1): >>46190662 #
2. korianders ◴[] No.46190662[source]
One baffling thing I see people do with typedefing function pointers is insisting on adding in the pointer part in the typedef which just complicates and hides things.

If you want to typedef a function pointer, make a completely ordinary function declaration, then slap 'typedef' at the beginning, done. This does require you to do "foo_func *f" instead of "foo_func f" when declaring variables, but that is just clearer imo.

    typedef int foo_func(int); // nice

    typedef int (*foo_func)(int); // why?
replies(1): >>46195456 #
3. cryptonector ◴[] No.46195456[source]
Why do you need the `*` to be part of every variable/member declaration?