logoalt Hacker News

pcfwiktoday at 1:56 AM2 repliesview on HN

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

userbinatortoday at 7:24 AM

if you know how to use a variable, then you know how to read and write a declaration for it.

In other words, the precedence of operators in a declaration have exactly the same precedence as in its use.

nitrixtoday at 4:11 AM

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.

show 3 replies