well why would,
#include <iostream>
using namespace std;
int afunction () {return 0;};
int anotherfunction () {return 0;};
int main ()
{
cout << &afunction << endl;
}
give this,
1
The address is the memory location where the entity is stored. Every block of code in the program has its own memory location in the program. Which means like any variable or object methods and functions also have memory address.
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 afunction
from whatever its value actually is to true
or false
. Since you can't have a function at address 0
, the value printed is always true
, which cout
displays as 1
.
This illustrates why implicit conversions are usually frowned upon. If the conversion to bool
were explicit, you would have had a compile error instead of silently doing the wrong thing.
The function pointer type is not supported by std::ostream
out of the box. Your pointers are converted to only possible compatible type - bool
- and verything that is not zero is true
thanks to backward compatibility to C.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With