C Function Pointer Syntax: Two Ints to Float

In the C programming language, function pointers allow developers to store the memory address of executable code, pass functions as arguments, and build flexible callback systems. This article explains the precise syntax required to declare a function pointer that accepts two integer parameters and returns a float, highlighting the critical role of operator precedence and the use of type definitions for cleaner code.

The Correct Syntax

The standard syntax to declare a function pointer variable that takes two int parameters and returns a float is:

float (*func_ptr)(int, int);

In this declaration, func_ptr is the identifier of the pointer variable.

Syntax Breakdown

  • float: The return type of the function the pointer references.
  • (*func_ptr): The pointer declaration. The parentheses around *func_ptr are mandatory. Because the function call operator () has higher precedence than the dereference operator *, omitting these parentheses would change the meaning to float* func_ptr(int, int);, which declares a regular function returning a pointer to a float (float *).
  • (int, int): The parameter types accepted by the function. Variable names inside the parameter list are optional during declaration, so both (int, int) and (int a, int b) are valid.

Usage Example

To initialize and call a function using this pointer, define a matching function and assign its address:

#include <stdio.h>

float divide(int a, int b) {
    return (float)a / (float)b;
}

int main(void) {
    // Declare and initialize the function pointer
    float (*func_ptr)(int, int) = divide;

    // Call the function through the pointer
    float result = func_ptr(10, 4);

    printf("Result: %f\n", result); // Outputs: Result: 2.500000
    return 0;
}

Both func_ptr = divide; and func_ptr = &divide; are valid syntax in C, as the function name automatically decays into a pointer. Similarly, invoking the function can be written as func_ptr(10, 4) or explicitly dereferenced as (*func_ptr)(10, 4).

Simplifying with typedef

Declaring complex function pointer types repeatedly can lead to syntax errors and poor readability. You can create a reusable type alias using typedef:

typedef float (*MathFunc)(int, int);

Once defined, you can declare function pointers using the new type name directly:

MathFunc ptr = divide;
float result = ptr(7, 2);