Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I re-define a function or check if it exists?

Tags:

c

function

I have a question about (re-)defining functions. My goal is to have a script where I can choose to define a function or not. Like this:

void func(){}

int main(){
   if (func)func();
}

AND without the function, just:

int main(){
   if (func)func();
}

Anybody an idea?

like image 754
Tim Avatar asked Aug 02 '11 18:08

Tim


People also ask

How do you check if a function exists or not?

Please, some explanation. In two cases, simply call function_exists with the name of function parameter to check existence, returns bool.

How do you know a function is defined?

When the graph of a relation between x and y is plotted in the x-y plane, the relation is a function if a vertical line always passes through only one point of the graphed curve; that is, there would be only one point f(x) corresponding to each x, which is the definition of a function.

How do you know if a function exists using typeof operator?

The typeof operator gets the data type of the unevaluated operand which can be a literal or a data structure like an object, a function, or a variable. The typeof returns a string with the name of the variable type as a first parameter (object, boolean, undefined, etc.).

How do you check function is defined or not in jQuery?

With jQuery. isFunction() you may test a parameter to check if it is (a) defined and (b) is of type "function." Since you asked for jQuery, this function will tickle your fancy.


2 Answers

You can do this in GCC using its weak function attribute extension:

void func() __attribute__((weak)); // weak declaration must always be present

int main() {
  if (func) func();
  // ...
}

// optional definition:
void func() { ... }

This works even if func() is defined in another .c file or a library.

like image 88
bdonlan Avatar answered Sep 23 '22 00:09

bdonlan


Something like this, I think. Haven't used function pointers much, so I may have gotten the syntax slightly wrong.

  void func()
  {
#define FUNC_PRESENT
      // code
  }

  void (*funcptr)();

#ifdef FUNC_PRESENT
      funcptr = func;
#else
      funcptr = NULL;
#endif

  int main()
  {
      if (funcptr)
          funcptr();
  }
like image 26
JAB Avatar answered Sep 23 '22 00:09

JAB