Search code examples
c++atomicboolean-operations

Using negation operator ! with std::atomic<uint_32>


I have a working piece of code:

#include <atomic>
#include <cstdint>


int main()
{
    std::atomic<uint32_t> foo;

    foo = 5;
    std::cout << foo.load() << std::endl;

    if (!foo) // what is checked here????????????
    {
        std::cout << "!foo == TRUE\n";
    }
    else
    {
        std::cout << "!foo == FALSE\n";
    }


    return 0;
}

// Output : 
// 5
// !foo == FALSE

There is no bool operator on cppreference for std::atomic and CLion doesn't show it as operator. What is checked in if-condition?


Solution

  • What it is trying to do is convert it to a boolean value so that it can determine which block to run.
    Because 5 is a 'truthy' value, it is converting it to true, and then negating that to false. On the other hand, 0 is a 'falsy' value, so it becomes false negated to true.