Home > Back-end >  Questions about `std::cout << &std::hex << 123 << std::endl;`
Questions about `std::cout << &std::hex << 123 << std::endl;`

Time:04-10

Here is the code snippet:

#include <iostream>

int main()
{
    std::cout << std::hex << 123 << std::endl;

    std::cout << &std::hex << 123 << std::endl;
}
  1. What's &std::hex? I think it acquire the address of std::hex. And the address would be printed out.

  2. Is there any potential problem with this code snippet because somebody said it's bad to acquire the address of a function provided by the standard library?

CodePudding user response:

The name of a function decays into a pointer to that function. So std::cout << std::hex uses the stream inserter that takes a pointer to a function that takes an std::ios_base& and returns an std::ios_base&. The stream inserter simply calls the function.

Function pointers have another peculiar property: when you write &std::hex, it evaluates to the address of the function. Same for &&std::hex, &&&&std::hex, etc. They all mean the same thing.

  •  Tags:  
  • c
  • Related