0
#include "alotMonster.h"
#include "troll.h"

// alotMonster has a function named createAlotMonster()
// troll has a function named createTroll()

int main (void) {
   createAlotMonster(createTroll()); 
}

  // The function createTroll() is then saved inside a variable within createAlotMonster for later use.

How exactly can something like this be achieved in c? So basically storing a function call from one header inside another header.

Asperger
  • 3,064
  • 8
  • 52
  • 100
  • 1
    See https://stackoverflow.com/questions/840501/how-do-function-pointers-in-c-work – Mankarse Nov 04 '16 at 09:35
  • Unclear question. You might want to use [function pointers](https://en.wikipedia.org/wiki/Function_pointer). Be aware that C does not have *genuine* [closures](https://en.wikipedia.org/wiki/Closure_%28computer_programming%29). Read about [callbacks](https://en.wikipedia.org/wiki/Callback_%28computer_programming%29). Please make the difference between functions and function calls. – Basile Starynkevitch Nov 04 '16 at 09:37

1 Answers1

3

A "function call" is not an object in C, i.e. it's not something you can store. A call is an action, it happens when a function is called. It's not something that has a size, i.e. it can't be stored.

You might want a function pointer, which is a way of referencing functions for calling later.

If we were to invent some prototypes, let's say

int createTroll(const char *name, int strength);

then you can reference that function using a pointer like this:

int (*troll_function)(const char *, int) = createTroll;

so you would have createAlotMonster() take such a pointer:

vod createAlotMonster(int (*monster_function)(const char *, int));

Then you can call it almost like you showed:

createAlotMonster(createTroll);

Note that there are no () after createTroll, we're not calling the function just passing its address to createAlotMonster().

Also note that there is no "storing inside header", headers can't store data. They can't do anything, they are just source files with declarations. The code that implements createAlotMonster() must be adjusted in order to support taking a function pointer as an argument for this to work, you can't force it to do something it wasn't designed to do.

unwind
  • 391,730
  • 64
  • 469
  • 606