1

Possible Duplicate:
How to understand complicated function declarations?
Spiral rule and ‘declaration follows usage’ for parsing C expressions

There is a section with the same title, "Complicated Declarations", in K&R's The C Programming Language book as you might have already read. I am just reading the book and trying to better myself in C language. After reading the section mentioned, I think I couldn't get the logic behind the syntax of C declaration statements. 1, 2, 3 and 4 are from that section 5 and 6 are from other pages.

  1. int (*daytab)[13] daytab: pointer to array[13] of int

  2. void (*comp)() comp: pointer to function returning void

  3. char (*(*x())[])() x: function returning pointer to array[] of pointer to function returning char

  4. char (*(*x[3])())[5] x: array[3] of pointer to function returning pointer to array[5] of char

  5. typedef int (*PFI)(char *, char *) creates the type PFI, for ``pointer to function (of two char * arguments) returning int. How does the syntax works here?

Finally, my questions are:

  • Can you explain your ways of thinking and reading complicated declarations possibly by using examples above?
  • Are the things like 1,3,4 practically usable and needed? If so, can you write some code examples?
Community
  • 1
  • 1
woryzower
  • 956
  • 3
  • 15
  • 22

2 Answers2

6

I saw The ``Clockwise/Spiral Rule'' on HackerNews in the past week or so. It is a good way to think about C declarations, especially function pointers.

Kyle Burton
  • 26,788
  • 9
  • 50
  • 60
2

Look at the identifier and the symbol next to it to the right:

  • If it's a [ the identifier is for an array.
  • If it is a ( the identifier is for a function
  • If it is a ) look to the left and you will find a *: the identifier is a pointer
  • If there is nothing to the right or to the left, the identifier is a "plain old" object.

Elaboration:

  1. int (*daytab)[13]
    daytab is a pointer

  2. void (*comp)()
    comp is a pointer

  3. char (*(*x())[])()
    x is a function

  4. char (*(*x[3])())[5]
    x is an array

  5. typedef int (*PFI)(char *, char *)
    PFI is a pointer

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
pmg
  • 106,608
  • 13
  • 126
  • 198
  • Could you please give the complete meanings of each of these examples? Thanks a lot! – qed Aug 09 '13 at 11:47