pointers to functions, HELP

Victor Kan kan at dg-rtp.dg.com
Thu Oct 26 06:26:06 AEST 1989


In article <20057 at ut-emx.UUCP> mike at ut-emx.UUCP (Mike O'Donnell) writes:
>
>Although pointers to functions are not totally new to me, I have
>begun some experimentation with them and have a few questions.
>
>1.  If possible, how does one declare a function that returns
>    a pointer to a function?  And if possible, how does one use it?
>
>2.  How do you declare an array of pointers to functions?
>
>Any help and suggestions will be greatly appreciated.
>
>Thanks, Mike O'Donnell
>

This code works in GNU cc 1.35 running on an DG AViiON (m88k) running Unix.
I wouldn't be surprised if Microsoft C 5.0 (the piece of #*%&@#!) barfs on 
it though.

-- cut here --

#include <stdio.h>

typedef int (*pointer_to_function_returning_int)();

typedef pointer_to_function_returning_int (*pointer_to_function_returning_pointer_to_function_returning_int)();

/* to answer question #2: */
pointer_to_function_returning_int array_of_pointers_to_functions[100];

int returns_int();
pointer_to_function_returning_int returns_pointer_to_function_returning_int();

int
returns_int()
{
  printf ("returns_int() works!\n");
  return (1);
}

/* I haven't tried this without the typedefs, but I'm sure
 * you don't want to try either!!!
 */
pointer_to_function_returning_int
returns_pointer_to_function_returning_int()
{
  printf ("returns_pointer_to_function_returning_int() works!\n");
  return (returns_int);
}

main()
{
  pointer_to_function_returning_int p1;
  pointer_to_function_returning_pointer_to_function_returning_int p2;

  p1 = returns_int;
  p2 = returns_pointer_to_function_returning_int;

  (*p1)(); /* not too bad */
  (*(*p2)())(); /* really disgusting, but beautiful in a weird sort of way */
}

-- cut here --

The output looks like this:

returns_int() works!
returns_pointer_to_function_returning_int() works!
returns_int() works!


| Victor Kan               | I speak only for myself.               |  ***
| Data General Corporation | Edito cum Emacs, ergo sum.             | ****
| 62 T.W. Alexander Drive  | Columbia Lions Win, 9 October 1988 for | **** %%%%
| RTP, NC  27709           | a record of 1-44.  Way to go, Lions!   |  *** %%%



More information about the Comp.lang.c mailing list