How to print function pointers with cout?

前端 未结 7 2428
挽巷
挽巷 2020-11-22 07:09

I want to print out a function pointer using cout, and found it did not work. But it worked after I converting the function pointer to (void *), so does printf with %p, such

相关标签:
7条回答
  • 2020-11-22 07:33

    You can think of a function pointer as being the address of the first instruction in that function's machine code. Any pointer can be treated as a bool: 0 is false and everything else is true. As you observed, when cast to void * and given as an argument to the stream insertion operator (<<), the address is printed. (Viewed strictly, casting a pointer-to-function to void * is undefined.)

    Without the cast, the story is a little complex. For matching overloaded functions ("overload resolution"), a C++ compiler gathers a set of candidate functions and from these candidates selects the "best viable" one, using implicit conversions if necessary. The wrinkle is the matching rules form a partial order, so multiple best-viable matches cause an ambiguity error.

    In order of preference, the standard conversions (and of course there also user-defined and ellipsis conversions, not detailed) are

    • exact match (i.e., no conversion necessary)
    • promotion (e.g., int to float)
    • other conversions

    The last category includes boolean conversions, and any pointer type may be converted to bool: 0 (or NULL) is false and everything else is true. The latter shows up as 1 when passed to the stream insertion operator.

    To get 0 instead, change your initialization to

    pf = 0;
    

    Remember that initializing a pointer with a zero-valued constant expression yields the null pointer.

    0 讨论(0)
提交回复
热议问题