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

Viewed 17254

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=]

2 Answers

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

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