Interpreting Declarations
suggest changeA distinctive feature of C syntax is that a declarator resembles an expression that uses the declared identifier. For example, *p suggests that p is a pointer, while a[10] suggests that a is an array.
The following declarator operators determine how a declaration is grouped:
[], which declares an array;(), which declares a function;*, which declares a pointer;- grouping parentheses, which override the usual grouping.
| Declarator | Relative precedence | Associativity |
|---|---|---|
[] (array) |
higher | left to right |
() (function) |
higher | left to right |
* (pointer) |
lower | right to left |
To interpret a declaration, start at the identifier and work outward. Apply adjacent operators according to the precedence and associativity above, translating them with these phrases:
| Form | Interpretation |
|---|---|
thing[X] |
thing is an array of X elements of... |
thing(t1, t2, t3) |
thing is a function taking t1, t2, and t3, and returning... |
*thing |
thing is a pointer to... |
Finish with the declaration specifiers to the left of the declarator.
Examples
char *names[20];
Because [] binds more tightly than *, names is an array of 20 pointers to char.
char (*place)[10];
The parentheses make * apply first: place is a pointer to an array of 10 char elements.
int fn(long, short);
fn is a function taking a long and a short, and returning int.
int *fn(void);
Because () binds more tightly than *, fn is a function taking no arguments and returning a pointer to int.
int (*fp)(void);
The parentheses make * apply first: fp is a pointer to a function taking no arguments and returning int.
int arr[5][8];
arr is an array of five arrays, each containing eight int elements.
int **ptr;
ptr is a pointer to a pointer to int.
Multiple Declarations
A comma can separate multiple declarators that share the same declaration specifiers. It is a separator here, not the comma operator:
int fn(void), *ptr, (*fp)(int), arr[10][20], num;
This statement declares:
fn, a function taking no arguments and returningint;ptr, a pointer toint;fp, a pointer to a function takingintand returningint;arr, an array of 10 arrays, each containing 20intelements;num, anintobject.
Although C permits declarations like this, separate declarations are often easier to read when the declarators have different shapes.
Reading Declarations as Uses
Declarations can also be understood by imagining expressions that use the declared identifiers:
char *items[20]; /* *items[5] has type char. */
int fn(char); /* fn('b') has type int. */
int (*fp)(void); /* (*fp)() has type int. */
char *grid[10][20]; /* *grid[5][15] has type char. */
This technique is useful for ordinary declarations. For more complicated types, a typedef can make the intended structure clearer.