Written on January 12th, 2007.

A few days ago I was playing around with C, and I ended up writing a cute function pointer example. Here it is:

#include <stdio.h>

/* shouting */
void say_loud(char *a_message)
{
    printf("\"%s!!!\" you shout.\n", a_message);
}

/* whispering */
void say_soft(char *a_message)
{
    printf("\"%s\" you whisper.\n", a_message);
}

/* say function pointer */
void (*say)(char *a_message) = NULL;

int main(void)
{
	/* shout */
	say = say_loud;
	say("WHAT");

	/* whisper */
	say = say_soft;
	say("I know a secret!");

	return 0;
}

Compile and run. The output should be:

"WHAT!!!" you shout.
"I know a secret!" you whisper.

The code above uses a bit of syntactic sugar. Firstly, the functions say_soft and say_loud themselves are not being assigned to the say function pointer; their addresses are. Secondly, when calling the function, the function pointer has to be dereferenced first. Therefore, a “better” version of the main function would be this:

int main(void)
{
	/* shout */
	say = &say_loud;
	(*say)("WHAT");

	/* whisper */
	say = &say_soft;
	(*say)("I know a secret!");

	return 0;
}

However, I still prefer the former, considering the amount of line noise in the second example. The first example is correct, after all.

As for why I wrote this example in the first place… I was browsing Wikipedia’s article about Lua, and I noticed that functions can be stored in variables. This also means you can replace any function with another one, which is what one of the examples in the article shows:

do
    local oldprint = print
    print = function(s)
        if s == "foo" then
            oldprint("bar")
        else
            oldprint(s)
        end
    end
end

I wanted to try something similar in C. Of course, C does not have anonymous functions, but you can store functions (well, function addresses) in variables.