'How can I print value of std::atomic<unsigned int>?

I am using std::atomic<unsigned int> in my program. How can I print its value using printf? It doesn't work if I just use %u. I know I can use std::cout, but my program is littered with printf calls and I don't want to replace each of them. Previously I was using unsigned int instead of std::atomic<unsigned int>, so I was just using %u in the format string in my printf call, and therefore printing worked just fine.

The error I'm getting when trying to print the std::atomic<unsigned int> now in place of the regular unsigned int is:

error: format ‘%u’ expects argument of type ‘unsigned int’, but argument 2 has type ‘std::atomic<unsigned int>’ [-Werror=format=]



Solution 1:[1]

template<typename BaseType>
struct atomic
{
    operator BaseType () const volatile;
}

Use a typecast to pull out the underlying value.

printf("%u", unsigned(atomic_uint));

Solution 2:[2]

another option, you can use the atomic variable's load() method. E.g.:

std::atomic<unsigned int> a = { 42 };
printf("%u\n", a.load());

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 John Kugelman
Solution 2 Gabriel Staples