Hacker News new | comments | show | ask | jobs | submit login

It's worth noting that two of the example programs in K&R are a simple parser and "unparser" for (a subset of, but still quite complete) the declaration syntax, and it is only a few dozen lines.

IMHO the biggest difficulty that beginners face with the syntax is entirely because they attempt to parse it left-to-right and aren't following the precedence; once you realise that the operators (), [], and * in declarations have the exact same precedence they do in the rest of the language, and that expressions like 2 * (3 % foo(i + 4 / x[j])) - 1 are not read left-to-right either, it all comes together and makes perfect sense.

Starting at the identifier (or where it would go, if it was an abstract declarator) and reading outwards following the precedence rules (and recursively applying this to function calls) is the only correct way to parse these declarations, and it is basically what the example program in K&R illustrate.

Thus the "clockwise spiral rule" mentioned in the post is applicable only to certain cases and incorrect in general, as Linus Torvalds explains: https://plus.google.com/+gregkroahhartman/posts/1ZhdNwbjcYF

Edit: upon pondering the example

    int f((((((((((((((((((((((((((((((((((()))))))))))))))))))))))))))))))))));
I do not think it is legal in C89/90/99/11, since a parameter-declaration must begin with declaration-specifiers, and the declaration-specifiers cannot begin with an opening parenthesis. (Go to http://www.quut.com/c/ANSI-C-grammar-y.html and start following the rules via declaration->init_declarator_list->init_declarator->declarator->direct_declarator->parameter_type_list->parameter_list->parameter_declaration.)

On the other hand, I believe this:

    int f(int(((((((((((((((((((((((((((((((((()))))))))))))))))))))))))))))))))));
is legal and the type of the parameter is (pointer to) function returning int, with plenty of redundant parentheses around the abstract declarator.

Thanks for that comment, I'll read over that thread to see if I missed anything. Upon closer reading of the spiral rule, I don't think I have actually been following it as closely as I thought, so I don't think it affects the correctness of any other parts of the article. All this time, I had been kind of thinking that the spiral rule was a sort of 'gold standard' way to remember how to read declarations, but it doesn't clearly explain how to parse stuff like


Applications are open for YC Winter 2018

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | DMCA | Apply to YC | Contact