well why would,
#include <iostream>
using namespace std;
int afunction () {return 0;};
int anotherfunction () {return 0;};
int main ()
{
cout << &afunction << endl;
}
give this,
1
- why is every functions address true?
- and how then can a function pointer work if all functions share (so it seems) the same addresss?
The function address isn’t “true”. There is no overload for an ostream that accepts an arbitrary function pointer. But there is one for a boolean, and function pointers are implicitly convertable to bool. So the compiler converts
afunctionfrom whatever its value actually is totrueorfalse. Since you can’t have a function at address0, the value printed is alwaystrue, whichcoutdisplays as1.This illustrates why implicit conversions are usually frowned upon. If the conversion to
boolwere explicit, you would have had a compile error instead of silently doing the wrong thing.