2

I have two functions

void foo1(int);
void foo2(int);

i.e. both have the same signature. I have a function pointer

typedef void (*func_pt)(int)

that can point to either foo1 or foo2 e.g.

 if (match_condition) {
   func_pt = foo1;
}
else {
   func_pt = foo2;
}

Later in the code, I need to find out if func_pt is pointing to foo1 or foo2.

This code if (func_pt == foo1) seems to work.

Is this recommended and safe? If not, is there any alternative to findng out which function does a function pointer point to?

I don't understand how C compiler can figure out the equality. Is it just that the when the compiler sees foo1, it finds the address of the code where the function instructions are stored?

Thanks for any answers

Jongware
  • 22,200
  • 8
  • 54
  • 100
doon
  • 2,311
  • 7
  • 31
  • 52
  • Both are pointers, and have the same type. There's nothing wrong. – simonzack Oct 12 '14 at 11:13
  • Related (C++): http://stackoverflow.com/q/12898227/694576 – alk Oct 12 '14 at 11:15
  • I posted an answer in what case the pointers might not be equal. http://stackoverflow.com/questions/13600128/is-it-safe-to-pass-function-pointers-around-and-compare-them-just-like-normal-ob/26324729#26324729 – 2501 Oct 12 '14 at 12:00
  • Thanks. This is indeed a duplicate. Before posting my question, I did a search but did not find anything. I searched for quite a while actually. I probably need to hone my searching skills. Thanks to all those who answered. Very useful – doon Oct 12 '14 at 13:59

1 Answers1

2

Yes, it is safe. From [6.5.9] of the C99 standard (emphasis mine):

Two pointers compare equal if and only if both are null pointers, both are pointers to the same object (including a pointer to an object and a subobject at its beginning) or function, both are pointers to one past the last element of the same array object, or one is a pointer to one past the end of one array object and the other is a pointer to the start of a different array object that happens to immediately follow the first array object in the address space.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680