YOUR C LEARNING COMPANION

Find your next idea.

Learning path
Designing dataChapter 38 of 73

Function pointers and callbacks

Pass a choice of behavior through a compatible function pointer, and state the call and lifetime contracts.

5 min readDevelopingC17 baseline
Offline reading
In this chapter8 sections
0% through this chapter

Sometimes an operation should accept a choice of behavior. A sort needs a comparison rule; a transformation needs a function to apply. A function pointer lets us supply that choice without rewriting the surrounding operation.

1. Read the function type first

int (*operation)(int, int) declares a pointer to a function that takes two ints and returns int. The parentheses matter. int *operation(int, int) instead declares a function returning a pointer. A typedef such as Operation below names the pointer type; it does not introduce a new ownership rule.

A function designator ordinarily converts to a pointer to that function. That is why assigning add to operation works. You may also write &add. Calling operation(7, 2) uses the selected function. It does not copy the function’s instructions into the pointer object.

2. Copying the pointer copies the choice

Complete C17 program
#include <assert.h>

typedef int (*Operation)(int, int);

static int add(int left, int right) { return left + right; }
static int subtract(int left, int right) { return left - right; }

int main(void)
{
    Operation operation = add;
    assert(operation(7, 2) == 9);
    operation = subtract;
    assert(operation(7, 2) == 5);
    Operation saved = operation;
    operation = add;
    assert(saved(7, 2) == 5);
    return 0;
}

All calls above use small inputs whose sums and differences fit in int. Reassigning operation changes the selected function for later calls through that object. The saved pointer still selects subtract. This is the same value-copy principle you met with object pointers.

3. A callback is supplied behavior

A callback is a function supplied for another operation to call. The name does not imply an asynchronous event, a new thread, or a later time. This example calls the supplied function immediately, once for each element. Its surrounding loop owns the traversal; the callback owns the single-value transformation.

Complete C17 program
#include <assert.h>
#include <stddef.h>

typedef int (*Transform)(int);

static int increase(int value) { return value + 1; }

/* items: count writable ints; transform: valid compatible function.
   Every call and stored result must meet that function's contract. */
static void transform_each(int *items, size_t count, Transform transform)
{
    for (size_t i = 0; i < count; ++i) items[i] = transform(items[i]);
}

int main(void)
{
    int values[] = {1, 2, 3};
    transform_each(values, 3, increase);
    assert(values[0] == 2 && values[1] == 3 && values[2] == 4);
    return 0;
}

4. Compatibility is required at the call

The pointed-to function type must be compatible with the function actually called. Parameter count, parameter types, and return type participate in that contract. Casting an incompatible function pointer does not repair an invalid indirect call. A compiler accepting the cast is not evidence that the call is safe.

A function pointer may be null. A callback API must either reject a null pointer or define what its absence means before calling. Our transform_each contract requires a valid compatible function and count writable integer elements. The increase callback additionally requires a value whose increment fits in int.

5. Shared data needs its own contract

A C function pointer does not automatically bundle captured local variables. Some APIs accept a separate void * context pointer for callback data. That pointer still needs a valid target with enough lifetime. If the API stores a callback for later, find out when it may be called, how registration ends, and whether calls can overlap.

The object-pointer round-trip guarantee involving void * does not generally extend to function pointers. Keep function pointers in their appropriate types. Portable C also does not promise identical sizes or representations for every kind of pointer.

Think it through

Does “callback” guarantee the function runs in another thread?

Read the explanation

No. It describes who supplies the behavior. The receiving API decides when and where it calls the function; read that API’s contract.

Primary references and further reading

Before you move on

  • A function pointer selects a function without copying its code.
  • An indirect call must use a compatible function type and meet the called function’s contract.
  • A callback’s timing, context data, and concurrency rules come from the receiving API.
Keep these ideas separate
Callback / Asynchronous execution
Supplying a callback does not by itself imply another thread or a later invocation.
Explain it in your own words

What agreement does a caller need before giving another operation a callback and a data pointer?

Optional: say it aloud or keep a note. You can continue whenever you are ready.

Check your understanding

Optional. Answers are not saved or sent, and reading stays unrestricted.

Can a cast alone repair a callback whose function type is incompatible with the required callback type?
Read the explanation for every choice
  1. No. The eventual call must use a compatible function type.

    ✓ Correct reasoning. A cast does not change the function’s parameter and return contract.

  2. Yes, casting rewrites the function’s parameter types.

    Converting a pointer does not rewrite the function’s definition.

  3. Yes, every pointer type has identical call semantics.

    Object and function pointer roles and compatible function types still matter.

C17

Ready for the next idea?

Mark this chapter as read whenever you feel ready.

CHAPTER 38 / 73

In this chapter

Function pointers and callbacks

Search all 73 chapters in both languages.EN + HG

Try “pointer”, “why int”, or “undefined behavior”.

Concepts connect. Follow your curiosity.↑ ↓ to explore · Enter to open
MAKE YOURSELF COMFORTABLE

Your reading space

Appearance

A clear canvas with balanced contrast.

Text size

100%
AA

Reading tools

Your data stays in this browser

Export a backup before changing browsers or replacing an older version of the reader.

YOUR PERSONAL MARGINS

My notebook

Saved on this device
A LITTLE CLARITY

The glossary

A starting meaning, then a chapter to go deeper.

A QUICK DEFINITION

A little clarity

Read the full explanation →

A thought worth keeping