Print Volatile Pointer in C++23

Print Volatile Pointer in C++23

Working with volatile pointers is common in low-level programming, hardware interfacing, and concurrent code, where memory may change unexpectedly outside the current program flow. Displaying the address held by a volatile pointer can be tricky in earlier versions of C++, often requiring type casting to bypass compiler restrictions.

Before C++23, printing a volatile pointer typically involved casting it to a non-volatile pointer. While it works, this approach adds extra syntax and can obscure the intention of the code.

#include <iostream>

int main() {
    int x = 42;
    volatile int *p = &x;

    std::cout << p << std::endl; // 1
    std::cout << const_cast<int *>(p) << std::endl; // e.g. 0x7fff1211a5e4
}

Since C++23, it is possible to print volatile pointers directly without any casting or other workarounds. This improvement makes the code simpler and easier to read.

#include <iostream>

int main() {
    int x = 42;
    volatile int *p = &x;

    std::cout << p << std::endl; // e.g. 0x7fff1211a5e4
}

Leave a Comment

Cancel reply

Your email address will not be published.