[c] Understanding typedefs for function pointers in C

A function pointer is like any other pointer, but it points to the address of a function instead of the address of data (on heap or stack). Like any pointer, it needs to be typed correctly. Functions are defined by their return value and the types of parameters they accept. So in order to fully describe a function, you must include its return value and the type of each parameter is accepts. When you typedef such a definition, you give it a 'friendly name' which makes it easier to create and reference pointers using that definition.

So for example assume you have a function:

float doMultiplication (float num1, float num2 ) {
    return num1 * num2; }

then the following typedef:

typedef float(*pt2Func)(float, float);

can be used to point to this doMulitplication function. It is simply defining a pointer to a function which returns a float and takes two parameters, each of type float. This definition has the friendly name pt2Func. Note that pt2Func can point to ANY function which returns a float and takes in 2 floats.

So you can create a pointer which points to the doMultiplication function as follows:

pt2Func *myFnPtr = &doMultiplication;

and you can invoke the function using this pointer as follows:

float result = (*myFnPtr)(2.0, 5.1);

This makes good reading: http://www.newty.de/fpt/index.html

Examples related to c

conflicting types for 'outchar' Can't compile C program on a Mac after upgrade to Mojave Program to find largest and second largest number in array Prime numbers between 1 to 100 in C Programming Language In c, in bool, true == 1 and false == 0? How I can print to stderr in C? Visual Studio Code includePath "error: assignment to expression with array type error" when I assign a struct field (C) Compiling an application for use in highly radioactive environments How can you print multiple variables inside a string using printf?

Examples related to function-pointers

Passing capturing lambda as function pointer How can I pass a member function where a free function is expected? Using generic std::function objects with member functions in one class Function pointer as parameter Function pointer to member function Callback functions in C++ Python function pointer How can I call a function using a function pointer? Understanding typedefs for function pointers in C Calling C++ class methods via a function pointer

Examples related to typedef

How do I use typedef and typedef enum in C? Overloading operators in typedef structs (c++) What is the difference between 'typedef' and 'using' in C++11? typedef fixed length array Typedef function pointer? C++ template typedef dereferencing pointer to incomplete type uint8_t vs unsigned char typedef struct vs struct definitions Understanding typedefs for function pointers in C