Clockwise/Spiral rule helps in reading complex C/C++ declarations.
How you read below declarations:
char *(*fp)( int, float *);
void (*signal(int, void (*fp)(int)))(int);
int ** const ptr
How you use:
There are three simple steps to follow:
. Starting with the unknown element, move in a spiral/clockwise direction; when ecountering the following elements replace them with the corresponding english statements
[X] or []
Array X size of... or Array undefined size of...
(type1, type2)
function passing type1 and type2 returning..
*
pointer(s) to...
Keep doing this in a spiral/clockwise direction until all tokens have been covered.Always resolve anything in parenthesis first!
Let's learn by exaples:
char *str[10]
+-------+
| +-+ |
| ^ | |
char *str[10];
^ ^ | |
| +---+ |
+-----------+
- str is an array of 10 elements
- str is an array of 10, of pointers
- str is an array of 10, of pointers, of type char
char *(*fp)( int, float *)
+--------------------+
| +---+ |
| |+-+| |
| |^ || |
char *(*fp)( int, float *);
^ ^ ^ || |
| | +--+| |
| +-----+ |
+------------------------+
- fp is a pointer
- fp is a pointer, to function which takes argument int, float *)
- fp is a pointer, to function which takes argument int, float *), return pointer to
- fp is a pointer, to function which takes argument int, float *), return pointer to, char
void (*signal(int, void (*fp)(int)))(int);
+-----------------------------+
| +---+ |
| +---+ |+-+| |
| ^ | |^ || |
void (*signal(int, void (*fp)(int)))(int);
^ ^ | ^ ^ || |
| +------+ | +--+| |
| +--------+ |
+----------------------------------+
signal is a function passing an int and a pointer to a function passing an int returning nothing (void) returning a pointer to a function passing an int returning nothing (void)
const char *chptr;
chptr is a pointer to a char constant
char * const chptr;
chptr is a constant pointer to char
volatile char * const chptr;
chptr is a constant pointer to a char volatile
· int* - pointer to int
· int const * - pointer to const int
· int * const - const pointer to int
· int const * const - const pointer to const int
· int ** - pointer to pointer to int
· int ** const - a const pointer to a pointer to an int
· int * const * - a pointer to a const pointer to an int
· int const ** - a pointer to a pointer to a const int
· int * const * const - a const pointer to a const pointer to an int