Question

I need to make sure i understand some basic stuff first:

  1. how do i pass function A as a parameter to function B?
  2. how do i call function A from inside B ?

Now for the big whammy:

I'm trying to do something along the lines of this:

jmp_buf buf;
buf.__jmpbuf[JB_PC] = functionA;
longjmp(buf,10);

Meaning that I want to use longjmp in order to go to a function. How should I do it?

Was it helpful?

Solution

You need to use a pointer to a function. The syntax for declaring a function pointer is:

rettype (*)(paramtype1,paramtype2,...,paramtypeN)

So, for example, we might have the following code:

char functionA(int x)
{
      printf("%d\n",x):
      return 'a';
}

char functionB(char (*f)(int), int val)
{
       return f(val); // invokes the function pointer
}

int main(int argc, char* argv[])
{
       char result = functionB(&functionA,3); // prints "3"
       printf("%c\n",result); // prints 'a'
       return 0;
}

Also, a side note, that while &functionA takes the address of functionA, it is actually not necessary to use the ampersand there... I personally do it, since I think it makes it more clear that it is a function pointer. You invoke a function pointer using the same syntax that you would when invoking a function.

As for using jump buffers, I believe what you are doing is not something that can be relied upon. If you want to create a jump buffer and invoke setjmp before invoking some function, then later invoke longjmp so that you return to immediately prior to the call, then that is well-defined. The actual definition and structure of jmp_buf, though, is implementation-specific. There are certain requirements that it has to meet (e.g. it has to be an array type, because setjmp has to be able to take it by value and yet modify it), but other than that, the specification for setjmp.h does not define the structure of jmp_buf. So, anything that attempts to manipulate jmp_buf directly is going to be specific to a particular platform.

OTHER TIPS

  1. Passing functionA as a parameter to functionB:

    typedef void function_type(void);

    void functionA(void) { printf("This is function A\n"); }

    int main(int argc, char **argv) { functionB(&functionA); return (0); }

  2. Calling function A from function B:

    void functionB(function_type *func) { func(); }

  3. Using longjmp() to go to a function. The best answer is "Don't do this" - there's almost always a better way to achieve the same aim. Can you explain the situation where you need this?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top