Sunday, August 26, 2007

How to read C declarators PART 1

Reading C declarators in a precise manner.

The rule goes like this:

"Start at the variable name (or innermost construct if no identifier is present. Look right without jumping over a right parenthesis; say what you see. Look left again without jumping over a parenthesis; say what you see. Jump out a level of parentheses if any. Look right; say what you see. Look left; say what you see. Continue in this manner until you say the variable type or return type."


The degenerate case is:

int i;

Starting at i, you look right and find nothing. You look left and find the type int, which you say. Done.

Ok, now a more complicated one:

int *a[3];

Start at a. Look right, say array of size 3. Look left and say pointer. Look right and see nothing. Look left and say int. All together you say a is an array of size 3 pointers to int.

Adding parentheses is when it gets weird:

int (*a)[3];

The parentheses change the order just like in an expression. When you look right after a, you see the right parenthesis, which you cannot jump over until you look left. Hence, you would say a is a pointer to an array of 3 ints.


bye for now
Al

No comments: