Course contentsShow
← C
Lesson 516 of 1,2197. PointersFree lesson

Calling a function via a pointer

Calling a function via a pointer

What you'll learn: How to trigger a function's execution using a pointer variable instead of the function's name.

The remote control analogy

Think of a standard function call like walking up to a television and pressing the "Power" button directly on the frame. You know exactly which TV you are turning on because you are touching it.

Using a function pointer is like using a universal remote control. The remote isn't the TV itself; it is a device that holds a link to the TV. When you press "Power" on the remote, it sends a signal to whatever TV it is currently pointed at. By simply changing which "code" the remote is programmed with, you can use the same button to control a completely different device.

The syntax of the call

Once you have a function pointer that stores the address of a function, you execute it by treating the pointer variable as if it were the function name itself.

If you have a pointer named action, you call it by writing action();. While older versions of C sometimes required you to write (*action)();, modern C allows you to use the pointer name directly. The compiler sees the parentheses and understands that you want to jump to the memory address stored inside that pointer and run the code located there.

Seeing it in action

In the example below, we have two simple functions. We use one pointer to call them both at different times.

#include <stdio.header>

void sayHello() {
    printf("Hello, world!\n");
}

void sayGoodbye() {
    printf("See you later!\n");
}

int main() {
    // Declare a pointer to a function that returns void and takes no arguments
    void (*ptr)();

    // Point to sayHello and call it
    ptr = sayHello;
    ptr(); 

    // Point to sayGoodbye and call it
    ptr = sayGoodbye;
    ptr(); 

    return 0;
}

Why do this?

Calling a function via a pointer allows your code to be dynamic. Instead of hard-coding a specific behavior, your program can decide which function to run while it is actually staying in motion. This is the foundation for advanced techniques like "callbacks," where you tell a piece of code, "Here is a pointer; when you finish your task, call whatever function this is pointing to."

Key takeaway

To call a function via a pointer, use the pointer's name followed by parentheses and any required arguments, just as you would with a regular function name.