0

Possible Duplicate:
How to print function pointers with cout?

What is the difference between function pointers in c and c++? When I'm printing function pointer in c++ it's giving 1, but in c it's giving an address.

#include <iostream>

int fun()
{}

typedef int (*f)();


int main()
{
    f test = fun;
    std::cout << reinterpret_cast<f>(test);
}


#include <stdio.h>

int fun()
{}

int (*f)();

int main()
{
    f = fun;
    printf("%p", f);
}
Community
  • 1
  • 1
Paul Varghese
  • 1,635
  • 1
  • 15
  • 30

3 Answers3

4

The main difference is the printing mechanism you're using. std::cout and printf have different semantics. std::cout refers to your pointer as boolean data and prints either 0 or 1 instead of the address.

selalerer
  • 3,766
  • 2
  • 23
  • 33
4

The function pointer can't convert to void*, so in program using C++ i/o it converts to bool. The C program is also a C++ program. You should get no difference when you compile it as C++.

Cheers & hth.,

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
1

The real question is what's the difference between printf with "%p" and cout when you stream a pointer to a function.

To print out the pointer to function in C++, try casting it to a char* and iterating through the bytes (with length of sizeof(test)). I think you'll find it to be similar to "%p"

Lou Franco
  • 87,846
  • 14
  • 132
  • 192
  • +1 clever: I was just trying to think how to get around the problem with function pointers (method) potentially not fitting into a standard pointer. – Martin York Oct 21 '11 at 16:52