I want to handle the special case where multiplying two numbers together causes an overflow. The code looks something like this:
int a = 20;
long b = 30;
// if a or b are big enough, this result will silently overflow
long c = a * b;
That's a simplified version - in the real app, a and b are sourced elsewhere at runtime. What I want to achieve is something like this:
long c;
if (a * b will overflow) {
c = Long.MAX_VALUE;
} else {
c = a * b;
}
How do you suggest I best code this?
Update: a and b are always non-negative in my scenario.