Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 985
luizleroy Avatar asked Sep 09 '09 20:09

luizleroy


People also ask

What is private function in C?

Private Methods can only be used inside the class. To set private methods, use the private access specifier. Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members.

Are there private functions in C?

You can make module-private functions with the static keyword: static void func(void) { // ... } Then, func() can only be called by other functions defined in the same file (technically, the same translation unit: other functions whose definitions are included by a #include directive can still access it).

Can we make function private?

You should make a function private when you don't need other objects or classes to access the function, when you'll be invoking it from within the class. Stick to the principle of least privilege, only allow access to variables/functions that are absolutely necessary.


Video Answer


1 Answers

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 
like image 145
Chris Lutz Avatar answered Sep 21 '22 19:09

Chris Lutz