EmbLogic's Blog

syntax of c function pointer

1.Define a Function Pointer
Since a function pointer is nothing else than a variable, it must be defined as usual. In the following example we define a function pointers named pt2Function. It points to a function, which take one float and two char and return an int.
//  define a function pointer and initialize to NULL
int (*pt2Function)(float, char, char) = NULL;

2.Calling Convention….

Normally you don’t have to think about a function’s calling convention: The compiler assumes cdecl as default if you don’t specify another convention. However if you want to know more, keep on reading … The calling convention tells the compiler things like how to pass the arguments or how to generate the name of a function. Examples for other calling conventions are stdcall, pascal, fastcall. The calling convention belongs to a functions signature: Thus functions and function pointers with different calling convention are incompatible with each other!  For the GNU GCC you use the attribute keyword: Write the
function definition followed by the keyword attribute and then state the calling convention in double parentheses.

//  define the calling convention
void DoIt(float a, char b, char c) __attribute__((cdecl));
3.Assign an Address to a Function Pointer
It’s quite easy to assign the address of a function to a function pointer. You simply take the name of a suitable and known function or member function. Although it’s optional for most compilers you should use the address operator & infront of the function’s name in order to write portable code.
// assign an address to the function pointer..

int DoIt (float a, char b, char c){ printf(“DoIt\n”); return a+b+c; }
int DoMore(float a, char b, char c){ printf(“DoMore\n”); return a-b+c; }
pt2Function = DoIt; // short form
pt2Function = &DoMore; // correct assignment using address operator

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>