When I want to negate a number of type std::size_t, I usually do -static_cast<int>(number). However, I understand that the number might not fit into an int. So, my question is what is a safe portable way to do this?
When I want to negate a number of type std::size_t , I usually do
Share
There is no safe portable way to do this.
size_tis an unsigned type. There is no guarantee that there is any signed integer type big enough to hold the maximum value ofsize_t.If you’re able to assume that the value you’re negating isn’t too big, you can convert it to
long long(if your compiler supports it) orlong(if it doesn’t):If you’re worried about overflow, you can compare the value of
stoLLONG_MAXbefore doing the conversion.