logoalt Hacker News

pcfwiktoday at 4:28 PM3 repliesview on HN

Being taught this rule in undergrad really hampered my appreciation of C. As I've said in a previous comment, the real key that unlocked understanding C declarations for me is the mantra "declaration follows use." 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. Once I understood this elegant idea, it became hard to enjoy using statically typed languages that eschew it.

It is explained in more detail at this link: https://eigenstate.org/notes/c-decl


Replies

nitrixtoday at 5:03 PM

Some more examples:

  int v, *w, x[5], *y[5], (*z[5])(int, int);
Where v is an int, w is a pointer, x is an array, y is an array of pointers, z is an array of function pointers, etc.

Similarly, typedef is also just a keyword in front of a regular declaration.

  int foo[5];
  typedef int foo[5];

  int bar(void);
  typedef int bar(void);
Now you can use `bar *` as a function pointer.

The entire language works like this.

show 1 reply
IronFox05today at 5:57 PM

Call me a hater but I don't like the spiral rule and I like "declaration follows use" even less.

How do you make an std::array of a given type? Wrap the existing type in an extra layer of std::array, we all know this, it makes sense, there's no reasonable alternative. How do you make a C-array of a given type? Oh boy, "prepend the array specifier before the list of existing array specifiers" (actually it's worse because you have to find the right possibly-empty array of existing array specifiers first, just because there's a list of array specifiers somewhere in the type doesn't mean it's the one you should be prepending to).

"Declaration follows use" immediately goes out the window when faced with typedeffed types being used as the base type, or (as mentioned) generics in descendant languages of C. Instead you get "declaration builds up a type by wrapping layers around a core, use breaks down a type layer by layer starting from the outside" (so, necessarily, they mirror each other). C could have worked that way, and it would have made more sense.

"Declaration follows use" is the type level equivalent of taking off your socks before taking off your shoes because that's the order in which you put them on.

show 3 replies
kazinatortoday at 7:08 PM

If you explain declarations as following use, you are just moving the spiral parse from declarations to expressions. :)

show 1 reply