What is a function really?

Question:

What is really a function ?, Although this may seem very basic, I understood that functions are only used to divide the code in such a way that each block of it does something specific.

The doubt lies in something you hear today, one such memory address of a function . So I ask, if a function is just a block of code, how does it have a memory address?

#include <stdio.h>

double factorial(int a);

int main()
{
    int numero;
    printf("\n\n\t\t Direccion de memoria de la funcion 'factorial'  ==>  %i",&factorial);
}

double factorial(int a)
{
    if (a == 1 || a == 0)
    {
        return 1;
    }
    else
    {
        return a * factorial(a - 1);
    }
}

The fact that a function had a memory address made me wonder what a function really is.

Answer:

The answer varies from context. But I understand that your question is about the relationship between physical memory and the code you are writing.

At the end of the day the code you write is a 2nd, 3rd, or more abstraction of the "bits" (or consider referring to them as "the program") that will be stored in memory. Your program is really just a series of instructions. The programming language you have chosen is converted at some point into instructions for the computer. This program, when executed, moves from your hard disk to your RAM. And in this case, each instruction that you have given, consequently has a place in memory.

A function, in this context, is a block of instructions that you make "named". In the program that was compiled, when we run it, we do not know exactly where (that is, in what direction) the instructions are, but we do know that those instructions will be together. There are different use cases where that information could be useful, but "why do I want to know your address" is a different question.

In the example above, if you run that program on a normal computer, and print the address, you will notice that it changes every time you run the program. This is because the operating system "loads" your program (aka, your instructions) according to its memory management scheme. That is, I move it from your hard drive to RAM. Each time you do this it will be placed where the memory management scheme decides it is most convenient.

Expanding just a bit more, an example of when it is useful: when I have worked with assembly language, when creating interrupts I need to tell the system where to go when it happens, in this case, the address of the "function", or better called in this context "block instructions", is where the program should continue. In this context we would also call it a "subroutine". This is useful because I can't know the address of the function before running the program, but being able to "point" to the address is what allows it.

Note: My answer is not specific to C / C ++. The goal is to clarify the idea, not the implementation in some specific architecture.

Scroll to Top