Skip to content

Instantly share code, notes, and snippets.

@DrFrankenstein
Created November 7, 2017 16:32
Show Gist options
  • Save DrFrankenstein/c562b114eee44131e1064022af91c8a7 to your computer and use it in GitHub Desktop.
Save DrFrankenstein/c562b114eee44131e1064022af91c8a7 to your computer and use it in GitHub Desktop.
Exception-based isEven in C++. >;D
#include <limits>
#include <exception>
class OverflowException : public std::exception
{
};
struct SafeInt
{
int n;
SafeInt(int n) : n(n) { }
operator int() { return n; }
int operator +(int addend)
{
if (std::numeric_limits<int>::max() - addend > n)
throw OverflowException();
return n + addend;
}
};
bool isEven(SafeInt n)
{
try
{
if (n == std::numeric_limits<int>::max())
return false;
else
return isEven(n + 2);
}
catch (OverflowException ox)
{
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment