0

I am a bit confused now. So, if i write the following code:

int x = 5;
cout << &x << endl;

compile it and run, I'll get something like 0x920FC7D which is the normal hexadecimal value for memory locations. But when I compile and run the following code:

#include <iostream>
using namespace std;

void add(int a, int b){
    cout << a + b << endl;
}

void subtract(int a, int b){
    cout << a - b << endl;
}

void multiply(int a, int b){
    cout << a * b << endl;
}

int main(){

    void ( *operations[3] ) (int, int) = {add, subtract, multiply};

    int length = sizeof(operations)/sizeof(operations[0]);

    for(int i=0; i < length; ++i){
        cout << operations[i] << endl;
    }

    return 1;
}

I always get:

1
1
1

It seems the address of pointer should also be hexadecimal value, but even if it's binary or just decimal, why it is always the same?

Michael
  • 657
  • 4
  • 29

1 Answers1

4

If you take a look at the overloads for the operator << with a std::ostream& as the left hand operand, you'll find that there are no overloads for pointers to functions as right hand operand.

But you are inserting function pointers. So, what is being inserted? Well, function pointers are implicitly convertible to bool, and there is an overload for bool. All are 1 because all of the converted values are true. This is because none of the function pointers were null which is the only function pointer that converts to false.

eerorika
  • 232,697
  • 12
  • 197
  • 326