Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?
like image 992
code shogan Avatar asked May 16 '11 20:05

code shogan


People also ask

What is the address of a function in C?

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.


2 Answers

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.

like image 65
Dennis Zickefoose Avatar answered Sep 22 '22 13:09

Dennis Zickefoose


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.

like image 31
Nikolai Fetissov Avatar answered Sep 25 '22 13:09

Nikolai Fetissov