Saturday 9 February 2008

int *(*(*(*b)())[10])();

I've just read Terence Parr's post titled "How To Read C Declarations". The quoted "Golden Rule" makes reading declarations really easy even for a drunk ape, but it's one of the kind I dislike. It gives you some "magical" steps to follow (here are the same rules stated more verbosely in an awful, BASIC-ish GOTO-step-N manner) with no explanation why this way, no another.

Here is the missing explanation:

Declaration reflects how you use declared expression (how you get the value of it), so in int tab[]; tab is an array (you index it) of integers. int (*tab)[]; is a pointer to an array (you dereference it, then index). int *(tab[]); is an array of pointers — you have to index it, then dereference.

How about int *tab[]? You have to know operator precedence

It's not that hard as in looks like. In our case the rule of thumb is: "Postfix binds stronger than prefix.", so you read int *tab[] as array of pointers. "Postfix binds stronger than prefix" is the reason why you look right, then left, in "Golden rule".

Easy, isn't it? Now you know this post's title reads pointer to the function returning pointer to an array of pointers to functions returning pointers to integers. 10 is redundant in this case. (It's no 5 from here, I'm so lazy...).

Of course you'll find out that the Golden rule is an obvious result of sentences above. It's convinient to read declarations that way, but IMO it's very bad to actually think about declarations only in terms of now jump out of the parenthesis.

No comments: