Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Passing Functions

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
I need to pass a function as a variable to another function. I have looked everywhere and cannot figure out how to do this. Any help would be much appreciated.
 
Code:
/*
 Define the type of a function pointer
 with prototype.
 To understand a type declaration,
 just start from the name and expand
 respecting 'operator' precedence
 which is (from higher to lower):
   A) parenthesis surrounding name,
   B) parenthesis following name,
      array bracket (left to right)
   C) pointer before name (right to left)
   D) other type before name

 Here we have: int (*t_ptrFct)(int, int)
 which is
                  rule/description
 (*t_ptrFct)     : (A) t_ptrFct is a pointer to ...
 (...)(int, int) : (B) ... a function taking 2 ints ...
 int (...)(...)  : (D) ... and returning an int.

 Note that without the parenthesis we would have get:
    int *t_ptrFct(int, int)
 which is
  (B) a function ... 
  (C) ... returning a pointer to ...
  (D) ... an int
*/

typedef int (*t_ptrFct)(int, int);

/*
  One arg of the function is of the type just
  declared, i.e. a pointer to a function.
*/
int
callWithSquaredArgs(t_ptrFct myPtrFct,
		    int data1, int data2)
{
  /* Call function pointed by myPtrFct
     with arguments squared */
  (*myPtrFct)(data1*data1, data2*data2);
}

/* A simple minimum function */
int
minFct(int data1, int data2)
{
  return (data1 <= data2) ? data1 : data2;
}

/* A simple maximum function */
int
maxFct(int data1, int data2)
{
  return (data1 >= data2) ? data1 : data2;
}

/*
  To print expression and its value
  without duplication so avoiding the
  copy-paste-and-forget-to-change-both problem
*/
#define PRINT_EXP_AND_VALUE(EXP, TYPE) 	printf(&quot;%s = &quot;TYPE&quot;\n&quot;, #EXP, EXP)

int
main(int argc, char *argv[])
{
  /* call max function with args squared */
  PRINT_EXP_AND_VALUE
    (callWithSquaredArgs(&maxFct, 2, 3), &quot;%d&quot;);
  /* call min function with args squared */
  PRINT_EXP_AND_VALUE
    (callWithSquaredArgs(&minFct, 2, 3), &quot;%d&quot;);

  /*
    Note: 
    The PRINT_EXP_AND_VALUE macro are just for display.
    You can of course use callWithSquaredArgs alone.
  */
  printf(&quot;min squared = %d\n&quot;
	 &quot;max squared = %d\n&quot;,
	 callWithSquaredArgs(&minFct, 4, 5),
	 callWithSquaredArgs(&maxFct, 4, 5));
  return 0;
}

Below is my output from this code:
Code:
callWithSquaredArgs(&maxFct, 2, 3) = 9
callWithSquaredArgs(&minFct, 2, 3) = 4
min squared = 16
max squared = 25
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top