Templates[temp]

Function Pointer in C: What It Is and How It Works

Abstract

A function pointer in C is a variable that stores the address of a function, letting a program choose which function to call while it runs. Its type must match the function’s return value and parameters, and it can be called like a regular function or passed to other functions for callbacks and dispatch tables. Check pointers before calling them and keep signatures compatible, so runtime choices stay flexible without causing errors.

A hand holds a tag with an arrow pointing to one active mechanism among five on a shelf, highlighted by steel blue and vermilion accents.
Figure 1 — A hand holds a tag with an arrow pointing to one active mechanism among five on a shelf, highlighted by steel blue and vermilion accents.

Think of a remote with a button you can reassign to any channel. You don’t rewire the TV. You just point the button at a different target.

A function pointer in C works the same way: it stores the address of a function, so your program can choose which function to call while it runs.

This is the idea behind callbacks, custom sort comparisons, and dispatch tables.

The syntax is the tricky part, so we’ll walk through it step by step, then flag where C++ offers cleaner options and where the answer depends on the standard you compile with.

What Is a Pointer in C Function?

A pointer in C is a variable that holds the memory address of a value, so your code can reach that value through the address. Functions follow the same rule, so you can point at one too.

Every function has a memory address

Pointers exist for any data type. You can point at an int, a char, a struct, or another pointer, because each of them lives somewhere in memory. A function works the same way.

While the program runs, its machine code sits in memory, and that code has a starting address. Every function has one, main() included.

Consider a C++ developer who inherits a C plugin loader and wants to confirm which function the loader registered. Printing the address gives them a concrete value to check against what they expect.

[Example 1:
#include <stdio.h>

int main(void)
{
    printf("main() starts at %p\n", (void *)main);
    return 0;
}

— end example]

The number you see depends on your platform and may change between runs.

A developer points to a central memory block labeled main, connected by a dashed arrow in a diagram of numbered memory cells.
Figure 2 — A developer points to a central memory block labeled main, connected by a dashed arrow in a diagram of numbered memory cells.

Why %p prints addresses

The %p conversion specifier in printf is built for pointer values. It tells the library to print the address in a form the platform chooses, usually hexadecimal, so you don’t have to guess a format.

Using %d on a pointer is a mismatch that can print a garbage value, and it’s undefined behavior, meaning the program may do anything at all. Use %p for addresses, not for the values stored at them. That’s the whole job.

Declaring and Assigning Them in Code

A function pointer stores the address of a function, so you can call whichever function it holds. The syntax looks strange, but it’s one simple pattern.

How the declaration is written

Every function pointer declaration follows one shape: a return type, the name in (*name), then the parameters. The function type is what the pointer must match: the return type plus the parameter types, like int(int, int).

Two examples:

  • int (*int_op)(int, int); takes two ints and returns an int.
  • float (*scale)(float); takes one float and returns a float.

Parentheses make the difference. int *make(int, int); declares a function returning int*, while int (*make)(int, int); declares a pointer. The two look nearly identical, which is why the parentheses are easy to miss.

In C++, a function pointer can also be a template parameter, as in template <int (*Op)(int, int)>, so the target is fixed at compile time. C has no templates, so this part is for C++ readers.

A typedef gives the type a short name: typedef int (*IntOp)(int, int); lets you write IntOp op;. Picture a parser team whose handler signature appears in twelve places. One typedef means a signature change touches a single line.

A split ink drawing shows an asterisk pointer emerging free on the left, and clamped by parentheses pointing at the machine in vermilion on the right.
Figure 3 — A split ink drawing shows an asterisk pointer emerging free on the left, and clamped by parentheses pointing at the machine in vermilion on the right.

Pointing it at a function’s address

The compiler must see the function’s declaration first, so it can check the types. Then assign the name to the pointer:

int (*int_op)(int, int) = add;

The name converts to its address automatically, so &add works too. The pointer holds where the code lives; it doesn’t copy the code. Calling int_op(2, 3) jumps to add through that address. Declare first, then point.

Calling a Function Through Its Pointer

Calling through a function pointer looks almost identical to a normal call, and you’ll spot the differences at a glance.

Normal calls versus pointer calls

A direct call fixes which function runs when you write the code, while a pointer call leaves that choice until the program runs. Assuming fp points to add, these three lines return the same value:

[Example 2:
r = add(2, 3);
r = (*fp)(2, 3);
r = fp(2, 3);

— end example]

  • Explicit dereference: (*fp)(2, 3) applies the * to fp first, which makes the pointer obvious to anyone reading the code.
  • Omitted indirection: fp(2, 3) is equally valid, so the * is optional.
  • Same effect: either pointer form runs add and returns the same value as the direct call.

Walking through a full example

Consider a developer building a small calculator for a lab exercise who wants the operation chosen at runtime. This program stores add in a pointer, reads two numbers with scanf, and calls through it:

[Example 3:
#include <stdio.h>

int add(int a, int b) { return a + b; }

int main(void) {
    int (*fp)(int, int) = add;
    int x, y, result;

    printf("Enter two integers: ");
    if (scanf("%d %d", &x, &y) != 2) return 1;

    result = fp(x, y);
    printf("%d\n", result);
    return 0;
}

— end example]

The program runs in three steps:

  1. Assign: fp receives the address of add.
  2. Call: fp(x, y) runs add on the values the user typed.
  3. Print: the result is written to the console.

Later you could point fp at a subtract function, and the call line wouldn’t change. That’s the payoff.

Advanced Ways to Use Them

Once you can store a function’s address, you can pass it around and choose which function runs later.

Sending a pointer into another function

Pass a function’s address as a parameter, and the callee decides when to call it. Inside, invoke it by dereferencing, as in (*op)(a, b):

[Example 4:
int func1(int a, int b) { return a + b; }
int func2(int a, int b) { return a * b; }
int apply(int (*op)(int, int), int a, int b) { return (*op)(a, b); }

— end example]

Passing func1 or func2 to apply picks addition or multiplication.

A callback is a function you hand to library code to call later. A tools developer sorting records with qsort writes a comparator such as int cmp(const void *a, const void *b).

The library calls it for each pair it compares, so one routine sorts any record type.

C++ adds two options. A plain pointer takes only a function’s address, while std::function takes any callable with a matching signature. A lambda can capture local state, so a game programmer’s effect timer needs no global variable. That flexibility is not free, so it helps to know what std function costs before adopting it.

A sorting machine processes records, guided by a brass tag with a vermilion arrow and a pouch, outputting sorted items on a conveyor.
Figure 4 — A sorting machine processes records, guided by a brass tag with a vermilion arrow and a pouch, outputting sorted items on a conveyor.

Storing pointers in an array

When the function isn’t known until runtime, store pointers in an array and let an index choose one. This is often called a dispatch table. A firmware developer reading opcodes from a serial link uses the byte as the index instead of a long if chain.

Here op_add, op_sub, op_mul, and op_div each take two ints and return an int:

[Example 5:
int (*ops[4])(int, int) = { op_add, op_sub, op_mul, op_div };

— end example]

Call an entry as ops[opcode](x, y).

Check the pointer before you call through it, since a null entry fails at runtime. A mismatched signature draws a compiler warning, a cast hides it, and the arguments arrive in the wrong shape. Match signatures exactly.

Once you can read a declaration like int (*op)(int, int), the rest of the topic falls into place.

Store the pointer, call through it, and typedef the type when the signature gets long, and callbacks and dispatch tables become ordinary tools instead of mysteries.

When you write C++, weigh std::function and lambdas against the raw pointer, and check which standard your build targets before you commit. Master the declaration, and everything built on it gets easier.

Questions

What is pointer in C programing?

A pointer in C is a variable that stores the memory address of another object or function. A function pointer stores a function’s address and can be used to call that function.

What is the definition of function in C?

A function in C is a named block of code that can take parameters, perform operations, and optionally return a value. For example, `int add(int a, int b) { return a + b; }` defines a function that returns the sum of two integers.

What does function type mean?

A function type describes a function’s return type and parameter types. For example, `int(int, int)` is the type of a function that takes two `int` parameters and returns an `int`.

How many types are in C programming?

There is no single fixed number of types in C, because types can be grouped and combined in different ways. The fundamental types include `char`, integer types, floating-point types, and `void`; C also has derived types such as pointers, arrays, and function types, as well as structs, unions, and enumerations.

Why is %p used in C?

`%p` is the `printf` conversion specifier for displaying a pointer value, such as a memory address. Pass the pointer as a `void *`, for example `printf("%p", (void *)ptr);`, because `%p` expects a `void *` argument.

Why is main() declared as static?

`main()` is not declared `static` by default, and a C program’s entry-point function should normally have external linkage. Declaring `main` as `static` is not a portable way to define a standard C program’s entry point; use `int main(void)` or `int main(int argc, char *argv[])`.

What are 10 examples of C?

Ten examples of C programs are: Hello World, a calculator, a number-guessing game, a factorial calculator, a prime-number checker, a Fibonacci sequence generator, a temperature converter, a linked-list implementation, a file-copy utility, and a sorting program. These are common beginner or practice projects written in C.

What is static in C with an example?

In C, `static` gives a file-scope function or variable internal linkage, so it is accessible only within that source file. For a local variable, `static` preserves its value between function calls. For example, `void count(void) { static int n = 0; printf("%d\n", ++n); }` prints an increasing count each time `count` is called.

Read next

  1. C++ templates: how to write function and class templatesTemplates · Miriam Castellanos · written for C++17
  2. std::function in C++: what it costs, what to use insteadTemplates · Miriam Castellanos · written for C++17
  3. Function Type Explained: Signatures Without the BodyTemplates · Miriam Castellanos