Saturday, November 8, 2008

Deciphering complex declarations in C

Deciphering complex declarations in C


Step 1:

Find the identifier in the declaration.

Step 2:

Find the symbol on the right of the identifier and decipher it. Continue like this until you run out of symbols or hit a ‘)’ symbol.

Step 3:

Look at the symbol to the left of identifier. Keep going left until you run out of parameters or hit a ‘(‘ symbol.

Step 4:

Keep repeating steps 3 and 4 until you form the complete declaration.


Examples :




1. int p;

p is an integer

2. int *p;

p is a pointer to an integer.

3. int *p [10];

p is an array of ten pointers.

4. int ( *p ) [10];

p is a pointer to an array of ten integers.

5. int ( *fptr ) ( double x );

fptr is a pointer to a function that has one double parameter and return an integer.

6. extern char * ( *fptr [ ] ) ( void );

fptr is an array whose elements have the type pointer to a function with no parameters, whose return value has the type pointer to c char. The extern keyword in the function declaration tells the compiler that the function is probably in another translation unit. By default the linkage is external in case of a function declaration.

7. float ( *fun( ) ) [3][10];

The identifier fun is a function whose return value is of type pointer to an array of three 1-D array each of which contains ten elements of type float.

8. int * ( *func( ) ) ( );

func is a function returning pointer to a function returning pointer to an integer.

9. int ( * ( *func ) ( char * , double ) ) [9][10];

func is a pointer to a function taking arguments a character pointer and a double returning a pointer to an array of size 9 of array of size 20 integers.

No comments: