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

Taking the address of a function

Taking the address of a function

What you'll learn: How to access the memory address where a function's instructions are stored using its name.

Functions live in memory too

So far, you’ve learned that variables live at specific addresses in your computer's RAM. When you create an int x = 10;, the computer sets aside a small cubby hole to store that number. Pointers allow us to point to that cubby hole.

But what about functions? When you write a function like void greet(), the compiler translates those lines of code into a series of machine instructions. These instructions also need a place to sit while the program is running. Just like variables, functions have a home in memory.

The address of a function is the starting point of its executable code. If you know this address, you can tell your program to "jump" to that location and start running the instructions found there.

The "Magic" of the function name

In C, the name of a function acts very similarly to the name of an array. When you use the name of a function without parentheses, it "decays" into a pointer to its own address.

Think of a function name as a street address for a recipe.

  • If you add parentheses greet(), you are following the recipe (calling the function).
  • If you use the name alone greet, you are just looking at the address written on the paper.

Seeing the address

You can actually print a function's address using the %p format specifier. While you usually won't need to print these addresses in a real app, seeing it proves that the function is a physical entity in your hardware.

#include <stdio.h>

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

int main() {
    // 1. Calling the function normally
    sayHello();

    // 2. Printing the address of the function
    // Notice we don't use parentheses here!
    printf("The function 'sayHello' is stored at: %p\n", (void*)sayHello);

    return 0;
}

In the code above, sayHello (without ()) evaluates to the memory address of the first instruction of that function. Whether you use sayHello or the explicit "address of" operator &sayHello, C treats them as the same thing: a pointer to the code.

Key takeaway

A function name without parentheses is a pointer to the starting address of that function’s code in memory.