Friday, September 16, 2022

[FIXED] How can I print value of std::atomic<unsigned int>?

Issue

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

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

Use a typecast to pull out the underlying value.

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


Answered By - John Kugelman
Answer Checked By - Robin (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.