I prefer using std::optional
for cases like this:
#include <optional>
std::optional<int> AndTwoNum(int N, int M, int i)
{
if ((i < 0) || (i > 31))
{
return std::optional<int>(); // I got nothing for ya
}
int mask = ~0 << i;
int N_modify = N & mask;
int M_modify = M & (~mask);
return std::optional<int>(N_modify | M_modify);
}
Then to use it:
auto n = AndTwoNum(...);
if (n) { // we got a value
int i = *n; // unpack the value
} else {
// no value
}
The bad news is, std::optional
is not part of the current (C++11) standard. As far as I know, it's slated to be part of C++14. So compiler support is spotty. You can also use Boost.Optional in the interim, which is what std::optional
is based on.
Another alternative is to return a std::pair<int, bool>
where the bool
portion is used to indicate whether or not the int has a valid value. This is, essentially, what std::optional
does, but with a cleaner interface.