Search This Blog

Aug 2, 2011

How to interpret complex c delarations

For example, how to interpret it int * (* (*fp1) (int) ) [10];

1. We have important rule "The Right-Left rule"
This is a simple rule that allows you to interpret any declaration. It runs as follows:
Start reading the declaration from the innermost parentheses, go right, and then go left. When you encounter parentheses, the direction should be reversed. Once everything in the parentheses has been parsed, jump out of it. Continue till the whole declaration has been parsed.
 One small change to the right-left rule: When you start reading the declaration for the first time, you have to start from the identifier, and not the innermost parentheses.

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

This can be interpreted as follows:
Start from the variable name -------------------------- fp1
Nothing to right but ) so go left to find * -------------- is a pointer
Jump out of parentheses and encounter (int) --------- to a function that takes an int as argument
Go left, find * ---------------------------------------- and returns a pointer
Jump put of parentheses, go right and hit [10] -------- to an array of 10
Go left find * ----------------------------------------- pointers to
Go left again, find int -------------------------------- ints.


2. Use cdecl tool
 $ apt-get install cdecl
 $ cdecl
 cdecl> explain int * (* (*fp1) (int) ) [10]
 declare fp1 as pointer to function (int) returning pointer to array 10 of pointer to int

Post a Comment