Home > Backend Development > C++ > How Can I Correctly Print Function Pointers in C using `cout`?

How Can I Correctly Print Function Pointers in C using `cout`?

Susan Sarandon
Release: 2024-12-30 02:07:09
Original
445 people have browsed it

How Can I Correctly Print Function Pointers in C   using `cout`?

Printing Function Pointers with cout

In C , printing function pointers directly using cout can be problematic. Instead, it is advisable to convert the function pointer to void* before printing it. This is demonstrated in the following code snippet:

#include <iostream>
using namespace std;

int foo() {return 0;}

int main()
{
    int (*pf)();
    pf = foo;
    cout << "cout << pf is " << pf << endl;
    cout << "cout << (void *)pf is " << (void *)pf << endl;
    printf("printf(\"%p\", pf) is %p\n", pf);
    return 0;
}
Copy after login

Output:

cout << pf is 1  
cout << (void *)pf is 0x100000b0c  
printf("%p", pf) is 0x100000b0c
Copy after login

As seen above, cout implicitly converts the function pointer to bool, resulting in the output 1. To print the actual address of the function, it must be cast to void*.

Function pointers of type void* can be printed directly using cout. This is because void* is a generic pointer type that can hold the address of any type, including function pointers.

Observing Member Function Pointers

Printing member function pointers using void* does not work due to their more complex structure. However, according to the C Standard, rvalues of function pointers can be converted to bool.

The above is the detailed content of How Can I Correctly Print Function Pointers in C using `cout`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template