How to implement a "private/restricted" function in C?

luizleroy picture luizleroy · Sep 9, 2009 · Viewed 46.3k times · Source

I was asked a very interesting question during a C interview: How can you implement a function f() in such a way that it can only be called from a particular g() function. If a function other than g() tries to call f() it would result in a compiler error.

At first, I though this could be done with function pointers and I could get close to blocking the call at runtime. But I was not able to think of a compile time strategy. I don't even know if this is possible using ansi C.

Does anyone have any idea?

Answer

Chris Lutz picture Chris Lutz · Sep 9, 2009

Here's one way:

int f_real_name(void)
{
    ...
}

#define f f_real_name
int g(void)
{
    // call f()
}
#undef f

// calling f() now won't work

Another way, if you can guarantee that f() and g() are the only functions in the file, is to declare f() as static.

EDIT: Another macro trick to cause compiler errors:

static int f(void) // static works for other files
{
    ...
}

int g(void)
{
    // call f()
}
#define f call function

// f() certainly produces compiler errors here