3

I am lost in this declaration - int (*(*foo)(double))[3];

My understanding is that this is an array with size 3 which element is a function pointer taking double and returning pointer to int. However, the correct explanation seems to be "pointer to function taking double and returning pointer to array of 3 int". The returning pointer to array of 3 int confuses me a lot as int and [3] far apart.

Why is that? What is the syntax or rule to declare variables like this complex?

Wayne Wang
  • 1,287
  • 12
  • 21

2 Answers2

8

You just read from the inside out remembering that postfix array ([]) and function "call" (()) bind tighter than prefix pointer (*):

      (*foo)              // foo is a pointer...
      (*foo)(double)      // to a function taking a double...
    (*(*foo)(double))     // returning a pointer...
    (*(*foo)(double))[3]  // to an array of 3...
int (*(*foo)(double))[3]; // ints

(To work out where to start you might want to work from the outside in, but you need to read back from the inside out to read the declaration in the conventional order.)

CB Bailey
  • 755,051
  • 104
  • 632
  • 656
5

You can use "clockwise spiral rule"

      +----------------------------------+
      |  +---------------------------+   |
      |  |   +--------------------+  |   |
      |  |   | +----+             |  |   |
      |  |   | |+--+|             |  |   |
      |  |   | |^  ||             |  |   |
 int  (  *   ( *foo)( double      )  [3 ];
   |  ^  ^   ^ ^   ||             |  |   |
   |  |  |   | +---+|             |  |   |
   |  |  |   +------+             |  |   |
   |  |  +------------------------+  |   |
   |  +------------------------------+   |
   +-------------------------------------+  

Thus, Identifier foo

  • is a pointer
  • to function taking double as argument returning
  • pointer to
  • array 3
  • of int
P0W
  • 46,614
  • 9
  • 72
  • 119
  • 2
    See [here](http://stackoverflow.com/questions/16260417/the-spiral-rule-about-declarations-when-is-it-in-error) for the merits of the spiral rule. – CB Bailey Jan 01 '14 at 15:21