Wednesday, November 12, 2014

Pointers Declaration Syntax : Simplified

Sorry for the small font, but it is necessary for better viewing and hence better understanding.
----------------------------------------------------------------------

T   *x[N]           // x is an N-element array of pointer to T
T  (*x)[N]          // x is a pointer to an N-element array of T
T   *f()            // f is a function returning a pointer to T
T  (*f)()           // f is a pointer to a function returning T
T  (*f())(int)      // f is a function returning a pointer to a                   function with an int parameter and returns T

T  (*f[N])(int)​     // f is an N-element array of pointers to                     functions with an int parameter and returns T.

Good, now, how to understand this declaration:
void (*signal(int signo, void (*func)(int)))(int); ?

Simply apply the previous rules to it, and it breaks down as :

       signal                                      // signal
       signal(                            )        // is a function
       signal(    signo,                  )        // with a parameter named signo
       signal(int signo,                  )        //   of type int
       signal(int signo,        func      )        // and a parameter named func
       signal(int signo,       *func      )        //   of type pointer
       signal(int signo,      (*func)(   ))        //   to a function
       signal(int signo,      (*func)(int))        //   taking an int parameter
       signal(int signo, void (*func)(int))        //   and returning void
      *signal(int signo, void (*func)(int))        // returning a pointer
     (*signal(int signo, void (*func)(int)))(   )  // to a function
     (*signal(int signo, void (*func)(int)))(int)  // taking an int paraneter
void (*signal(int signo, void (*func)(int)))(int); // and returning void


Now it's easy, isn't it ? ;-)


If the declaration syntax is changed like :
void (*(*signal)(int signo, void (*func)(int)))(int); ,
signal will be a pointer to a function with a parameter named .........etc........

3 comments:

Anonymous said...

Simple and to the point !
Thank you.

Anonymous said...

Simple, logical and with a smile at the end when u get it :D

Thanks a lot H
Keep up the great work :)

Hesham Eraqi said...

Thank you. I'm glad it was useful :-)