ramu
ramu

Reputation:

Can we call functions using function pointer in C?

Can we call functions using function pointer? if yes how?

Upvotes: 2

Views: 349

Answers (4)

Adam Liss
Adam Liss

Reputation: 48310

Yes. Trivial example:


// Functions that will be executed via pointer.
int add(int i, int j) { return i+j; }
int subtract(int i, int j) {return i-j; }

// Enum selects one of the functions
typedef enum {
  ADD,
  SUBTRACT
} OP;

// Calculate the sum or difference of two ints.
int math(int i, int j, OP op)
{
   int (*func)(int i, int j);    // Function pointer.

   // Set the function pointer based on the specified operation.
   switch (op)
   {
   case ADD:       func = add;       break;
   case SUBTRACT:  func = subtract;  break;
   default:
        // Handle error
   }

   return (*func)(i, j);  // Call the selected function.
}

Upvotes: 13

Sherm Pendley
Sherm Pendley

Reputation: 13612

Yes. Here's a good tutorial with examples.

Upvotes: 4

David L Morris
David L Morris

Reputation: 1511

Yes. An example:

Before code...

typedef int ( _stdcall *FilterTypeTranslatorType )
    (
        int TypeOfImportRecord,
        PMAType *PMA
    );


FilterTypeTranslatorType    FilterTypeTranslator = {NULL};

Now in the code...

PMAType *PMA;
HANDLE hFilterDll;

// assume DLL loaded
// Now find the address...
...
        FilterTypeTranslator[TheGroup] =
            ( FilterTypeTranslatorType ) GetProcAddress( hFilterDll,
                                                         "FilterTypeTranslator" );
...
// now call it


FilterTypeTranslator(1,PMA);
...  

Upvotes: 1

Ana Betts
Ana Betts

Reputation: 74652

Yes you can.

Upvotes: 2

Related Questions