C Language Neat Tricks #2 (Part I)

Like a variable in the C language, a function has an address — a location in memory. This fact shouldn’t be surprising to you. After all, the function has to sit somewhere. And my guess is that location doesn’t change as the program runs.

A function’s address is an attribute used as an argument in several C language functions. You may have seen this requirement in some C Library functions and perhaps even used a function address in your own code.

As an example, the qsort() function’s fourth argument is the name of the function that compares the values:

qsort(qarray,SIZE,sizeof(int),compare);

Above, compare is the name of the compare() function, which compares two values. (See my Lesson on the Quicksort.)

So how does that work?

Look at the qsort() statement above. When a function is used as an argument, the parentheses are absent. With the parentheses, the function is called and it does whatever. Minus the parentheses, the function’s address is returned.

Here’s sample code:

#include <stdio.h>

int function(void)
{
    return(42);
}

int main()
{
    printf("The value of function() is %d\n",
            function());
    printf("The address of function() is %p\n",
            function);

    return(0);
}

In the first printf() statement, the value generated by function() is returned.

In the second printf() statement, the address of function() is returned.

Here’s how the output looks on my computer:

The value of function() is 42
The address of function() is 0x10e95ce90

Obviously, the address shown on your screen will be different and output in a different format as well. The point is that without the parentheses, the compiler reads function as a memory location, a pointer.

As a pointer, a function also sports a variable type, which makes sense. If you want to get really weird, you can save a function’s address in a pointer variable and use that variable to call the function. I’ll show you that truly oddball construction in next week’s Lesson.

Leave a Reply