why is the address of a c++ function always True?

一曲冷凌霜 提交于 2019-12-21 13:12:13

问题


well why would,

#include <iostream>

using namespace std;

int afunction () {return 0;};

int anotherfunction () {return 0;};

int main ()
{
    cout << &afunction << endl;
}

give this,

1

  1. why is every functions address true?
  2. and how then can a function pointer work if all functions share (so it seems) the same addresss?

回答1:


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.




回答2:


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.




回答3:


There's no overload of operator<< for function pointers (except stream manipulators), but there is one for bool, so the function pointer is converted to that type before display.

The addresses aren't equal, but they're both non-null, and hence they both covert to true.




回答4:


There is no overloaded function: operator<<(ostream&, int(*)()), so your function pointer is converted into the only type that works, bool. Then operator<<(ostream&, bool) is printing the converted value: 1.

You may be able to print the function address like so:

cout << (void*)&afunction << endl;



回答5:


All addresses in C++ are non-zero, because zero is the NULL pointer and is a reserved value. Any non-zero value is considered true.




回答6:


There cannot be an overload for function pointers for the iostream << operator, as there are an infinite number of possible function pointer types. So the function pointer gets a conversion applied, in this case to bool. Try:

cout << (void *) afunction << endl;

Which will give you the address in hex - for me the result was:

0x401344



回答7:


Did you check anotherfunction() as well?

Anyway, C++ pointer addresses, like C pointer addresses, are usually virtual on most platforms and don't correspond directly to memory locations. Hence the value may be very small or unusual.

Also, they will always be true, as 0 is NULL, an invalid pointer, and anything that is over 0 is true



来源:https://stackoverflow.com/questions/6022881/why-is-the-address-of-a-c-function-always-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!