Search code examples
c++formattingcoutnullptr

Formatting `nullptr` on out stream as hexadecimal address, instead of `0`


How can I format a null pointer of any type, preferably including immediate nullptr, on out stream so it prints out like 0x000000000000 or even just 0x0 but something resembling an address value instead of a senseless 0 or terminate or whatever non-address-like? //(nil) or (null) I could accept too if not using printf.


Solution

  • You can make a pointer formatter, which can do the formatting in whatever way you prefer.

    For example:

    #include <cstdint>
    #include <iomanip>
    #include <ios>
    #include <iostream>
    #include <sstream>
    #include <string>
    
    static auto Fmt(void const* p) -> std::string {
        auto value = reinterpret_cast<std::uintptr_t>(p);
        constexpr auto width = sizeof(p) * 2;
        std::stringstream ss;
        ss << "0x" << std::uppercase << std::setfill('0') << std::setw(width) << std::hex << value;
        return ss.str();
    }
    
    int main() {
        char const* p = nullptr;
        std::cout << Fmt(p) << "\n";
        p = "Hello";
        std::cout << Fmt(p) << "\n";
    }