Why is the address of a C ++ function always True?

Ok why not

#include <iostream> using namespace std; int afunction () {return 0;}; int anotherfunction () {return 0;}; int main () { cout << &afunction << endl; } 

give it

1

  • Why do all functions address true?
  • and how then can a function pointer work if all functions share (so it seems) the same addresses?
+6
source share
7 answers

Function address is not true. There is no overload for ostream that accepts an arbitrary function pointer. But there is one for the boolean, and function pointers are implicitly converted to bool. Thus, the compiler converts afunction from any of its values ​​in fact to true or false . Since you cannot have a function at address 0 , the value printed is always true , which cout displayed as 1 .

This illustrates why implicit conversions are usually not approved. If the conversion to bool was explicit, you would have a compilation error instead of quietly doing the wrong thing.

+15
source

Function pointer type is not supported by std::ostream out of the box. Your pointers are converted only to a compatible type - bool - and everything that is not zero is true due to backward compatibility with C.

+3
source

There is no operator<< overload for function pointers (other than stream manipulators), but there is one for bool , so the function pointer is converted to this type before displaying.

Addresses are not equal, but both are not equal to zero, so they are both hidden to true .

+2
source

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

You can print the address of the function as follows:

 cout << (void*)&afunction << endl; 
+1
source

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

0
source

There can be no overload for function pointers for the iostream <operator, since there are an infinite number of possible types of function pointers. Thus, the function pointer gets the applied transformation, in this case - bool. Try:

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

What will give you the address in hexadecimal format - for me, the result was:

 0x401344 
0
source

Have you also checked anotherfunction() ?

In any case, C ++ pointer addresses, such as C pointer addresses, are usually virtual on most platforms and do not correspond directly to memory cells. Therefore, the value can be very small or unusual.

In addition, they will always be true, since 0 is NULL , an invalid pointer, and anything greater than 0 is true

-1
source

Source: https://habr.com/ru/post/888260/


All Articles