How to Print Function Pointers With Cout

How to print function pointers with cout?

There actually is an overload of the << operator that looks something like:

ostream & operator <<( ostream &, const void * );

which does what you expect - outputs in hex. There can be no such standard library overload for function pointers, because there are infinite number of types of them. So the pointer gets converted to another type, which in this case seems to be a bool - I can't offhand remember the rules for this.

Edit: The C++ Standard specifies:

4.12 Boolean conversions

1 An rvalue of arithmetic,
enumeration, pointer, or pointer to
member type can be converted to an
rvalue of type bool.

This is the only conversion specified for function pointers.

cout with pointers c++

Because an int is (usually) 4 bytes 65 will fit quite neatly into just the first byte and the rest of the memory allocated for the int will be 0 this byte pattern happens to match up very closely to how strings are stored in memory.

So when the memory is accessed through a char* it will print A most of the time even though most of the prints were ill formed

int v = 65;  // Byte pattern on most machines [65,0,0,0] 
int* q = &v;
char** o = (char**)&q; // *o now points to [65,0,0,0] ==> ['A','\0','\0','\0'] ==> "A"
std::cout << o << std::endl;
// input: char**
// printed as: pointer
// result: 012FFCAC

std::cout << *o << std::endl; // Undefined Behaviour
// input: char*
// printed as: null terminated string
// result: "A"

std::cout << **o << std::endl; // Undefined Behaviour
// input: char
// printed as: single character
// result: 'A'

printf("%c",*o); // %c expects a [char] type but is given [pointer to char] ERROR
printf("%p",*o); // %p expects a [pointer] type and is given a [pointer to char] OK

Since a char is (usually) 1 byte there is no null terminand to stop the printing once it starts and it keeps printing whatever is around in memory until it runs into a 0 or an access violation

char v = 65;
std::cout << &v << std::endl; // &v is not a well-formed null terminated string: Undefined Behaviour
// input: char*
// printed as: null terminated string
// result: "A<whatever other data is around v in memory>"

Address of function pointers in C++ [duplicate]

There is some pointer here who seems not clear :

// pointer to a function
int (*fp)(int);
std::cout << "&fp=" << &fp << std::endl; // 0x7fff66da6810, address of pointer fp
std::cout << "fp=" << fp << std::endl; // 0, value of pointer fp

Here fp is undefined. Those lines have an undefined behaviour.

After that :

// function returns pointer to function
fptr fp_ptr = return_func_ptr();
std::cout << "&return_func_ptr=" << &return_func_ptr << std::endl; // 1
std::cout << "fp_ptr=" << *fp_ptr << std::endl; // 1
std::cout << "&fp_ptr=" << *fp_ptr << std::endl; // 1
// ^^^^^^^^^^ ^^^^^^^
std::cout << "*fp_ptr=" << *fp_ptr << std::endl; // 1

There are two things here :

  • On the line I pointed, I'm not sure it is what you wanted to test.
  • Also, cout doesn't have an overload to take a function pointer, it will take a bool instead. So it should be :

    std::cout << "fn_ptr=" << reinterpret_cast<void*>( fn_ptr ) << std::endl;

I would suggest you to read this article about function pointer, it explains almost all you need to know :

How to print member function address in C++

I don't believe that there are any facilities provided by the language for doing this. There are overloads for operator << for streams to print out normal void* pointers, but member function pointers are not convertible to void*s. This is all implementation-specific, but typically member function pointers are implemented as a pair of values - a flag indicating whether or not the member function is virtual, and some extra data. If the function is a non-virtual function, that extra information is typically the actual member function's address. If the function is a virtual function, that extra information probably contains data about how to index into the virtual function table to find the function to call given the receiver object.

In general, I think this means that it's impossible to print out the addresses of member functions without invoking undefined behavior. You'd probably have to use some compiler-specific trick to achieve this effect.

Hope this helps!

Is possible to fix the iostream cout/cerr member function pointers being printed as 1 or true?

Your overload works only for function pointers because the argument is a function pointer.

It doesn't work for member function pointers because member function pointers are not function pointers, as confusing as that might be. You could use a similar overload for member function pointers:

template<class C, class Ret, class... Args>
std::ostream& operator <<(std::ostream& os, Ret (C::*p)(Args...)) {
return os << "memfunptr " << "something...";

However, member function pointers are not convertible to void* so you cannot print them using void*. You need to decide what you would like to print in their case. If your goal is to get just some output that might hopefully be related to what member function is being pointed at, then you could do something like:

unsigned char* internal_representation = reinterpret_cast<unsigned char*>(&p);
for(std::size_t i = 0; i < sizeof p; i++)
os << std::hex << (int)internal_representation[i];

P.S. Converting a function pointer to void* is not allowed on all systems either. It is a conditionally supported feature. It'll probably work on all systems that use dynamic linking at least.

P.P.S. Adding overloads to standard class where all arguments are standard classes or fundamental types is probably potentially incompatible with a future language standard.

P.P.P.S. Taking address of main is technically not allowed.

How to print values of function pointer in C? [duplicate]

char const *(*fp)(void) = func;

Here, you are only assigning func to the function pointer. You need to call it to get the string returned by the function.

   char const *(*fp)(void) = func;

const char *p = fp();
printf("In main: %s", p);

That's how you print the string. There's no standard format specifier to print a function pointer. %p is only for data pointer, not for a function pointer. So to print a function pointer using %p is undefined behaviour.

If you really need to print the function pointer, then convert it to a character pointer and print them:

   unsigned char *cp = (unsigned char*)&fp;

for(i=0;i<sizeof fp; i++) {
printf("[%08x]", cp[i]);

This works because converting any object to a character pointer is allowed (char*, unsigned char* or signed char*). What it prints is in a implementation-defined format (just like %p).

Printing functions in cpp [duplicate]

It seems it is judging if the functions (converted to pointers to functions) are not null, returning true, and printing true as 1. This can be confirmed by adding cout << std::boolalpha; and seeing the the output is changed to true.

#include <iostream>
using namespace std;
void f1(){
cout<<"called function f";
int f2(){
cout<<"called f2";
return 1;
int main(){
cout << std::boolalpha;
cout << f2 <<endl; // prints true
cout << f1 <<endl; // also prints true

Why function pointer address is printing in bool type in c++?

Function pointers aren't convertible to data pointers. You'd get a compiler error if you were to try and assign one to a void* variable. But they are implicitly convertible to bool!

That is why the bool overload for operator<< is chosen over the const void* one.

To force the overload you want, you'd need to use a very strong C++ cast, that will almost completely ignore the static type information.

using namespace std;
int add(int x, int y)
int z;
z = x+y;

int main()
int a=10, b= 10;
int (*func_ptr) (int,int);
func_ptr = &add;
cout<<"The address of function add()is :"<< reinterpret_cast<void*>(func_ptr) <<endl;
(*func_ptr) (a,b);

Note that casting and treating function pointers as data pointers is only conditionally supported (from the C++ standard standpoint). Using it for anything other than casting back to the same function pointer will have an implementation specific outcome, that can very greatly among compilers.

Unexpected behaviour of std::cout [duplicate]

The printf call is simply undefined behavior. A function pointer is not an unsigned integer, and thus supplying it for a %u argument is not valid. (Try running this code on a 64-bit platform. You won't get the correct function pointer value.)

The cout on the other hand is type-safe. The compiler sees a function pointer argument and tries to find the best printing function (operator<< overload) it can. There is no such overload for function pointers themselves and the pointers don't offer a lot of implicit conversions. There is just one overload that works, and that is the one for bool. So the compiler converts the non-NULL function pointer to true and passes that. The overload then prints this as 1, but you could use the std::boolalpha modifier to make it print as true instead.

Related Topics

Leave a reply