Comment by stephencanon
14 years ago
The "spiral rule" makes for pretty pictures, but unfortunately it isn't correct. One simple example:
int *foo[3][4];
The spiral rule would have us read this as "foo is an array [3] of pointers to array [4] of int". What it actually is is "foo is an array [3] of arrays [4] of pointers to int".
The correct rule* for parsing declarations is "Start from the thing being declared, and read right until you hit a closing parenthesis, then read left until you reach the matching paren, then go back to reading right, and always skip over any tokens you've already read." This is sometimes called the "right-left rule"; it's not as pretty as "spiral", but it actually works.
(*) the really correct rule is "follow the syntax and semantics specified in the language standard", but for some reason that confuses people.
I think it works if you treat all the [] as a single token. foo is a 3x4 two dimensional array of pointers to int.
You can construct a rule along those lines that would work (though just taking all the [] at once doesn't suffice), but it ends up being precisely equivalent to the right-left rule, so I don't really see the point.
I think the point is that the spiral rule is just a way to remember/implement the right left rule.
But its not, there are no two dimensional arrays. There are arrays of arrays.
Yes, but does it matter? We can call that a 2D array.
The sizeof operator begs to differ.
3 replies →
Yes, the Right-Left rule is the one to use; I first read of it in Anderson & Anderson's _Advanced C: Tips & Techniques_. Having that simple rule, there's no need to struggle over qsort()'s declaration and others, or create unnecessary, one-use, typedefs.