4
#include<stdio.h>

int add(int i,int j)
{
        printf("\n%s\n",__FUNCTION__);

        return (i*j);
}

int (*fp)(int,int);

void main()
{
        int j=2;
        int i=5;

        printf("\n%s\n",__FUNCTION__);

        fp=add;

        printf("\n%d\n",(*fp)(2,5));
        printf("\n%s\n",*fp);
}
Christian Rau
  • 45,360
  • 10
  • 108
  • 185
  • 4
    What is 'void main' and why is this tagged c++? – nikolas Sep 18 '13 at 06:09
  • 4
    @nijansen With proper compiler settings, `void main()` is another compilation error :) – BЈовић Sep 18 '13 at 06:10
  • At run time, the names of functions are not known unless you stash them someplace. The linker just makes sure every reference to `add` refers to the same place, but the name "add" is not kept unless you specifically keep it. – David Schwartz Sep 18 '13 at 06:12
  • 1
    @nijansen `main` is where a program starts. `void main()` is an implementation-specific way to write the main function in a freestanding environment, fully compliant with the C standard. [More info here.](http://stackoverflow.com/questions/5296163/why-is-the-type-of-the-main-function-in-c-and-c-left-to-the-user-to-define/5296593#5296593) – Lundin Sep 18 '13 at 06:27

1 Answers1

4

You can compare the function pointer with a pointer to function. Like this :

    if (fp==add)
        printf("\nadd\n");

There are no other (standard) ways1.

This

printf("\n%s\n",*fp);

is a compilation error.


There are platform specific ways. For linux, this works :

#include<stdio.h>
#include <execinfo.h>

int add(int i,int j)

{

        printf("\n%s\n",__FUNCTION__);

        return (i*j);

}

int (*fp)(int,int);

union
{
    int (*fp)(int,int);
    void* fp1;
} fpt;

int main()
{
        fp=add;


        fpt.fp=fp;

        char ** funName = backtrace_symbols(&fpt.fp1, 1);
        printf("%s\n",*funName);
}
BЈовић
  • 62,405
  • 41
  • 173
  • 273
  • There are other ways, it's just very difficult—you have to parse the executable's symbol table and look up the address there. – Adam Rosenfield Sep 18 '13 at 06:15
  • @AdamRosenfield Those are platform specific (like a trick with backtrace). I meant, there are no standard ways – BЈовић Sep 18 '13 at 06:18
  • @BЈовић On linux "-rdynamic" option needs to be passed to gcc to get the names of the functions. – Vivek S Sep 18 '13 at 06:56