Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is value of variable always negative in case of overflow

It tried to solve this problem, given N,K amd M, find maximum integer T such that N*(K^T) <= M. N,K and M can be the values to 10^18. So long long is sufficient. I tried to solve it using iteration on T

int T = 0;
long long Kpow = 1;
while(1)
{
  long long prod = N*Kpow;
  if(prod > M)
    break;
  T++;
  Kpow = Kpow*K;
}

But since N*Kpow may go out of range of long long, there is need to handle the product using some big integer. But I found some other code which smartly handles this case

long long prod = N*Kpow;
if(prod < 0)
  break;

Even I have seen always, that in overflow, the value of variable becomes negative. Is it always the case or sometimes even positive values also occur in overflow case?

like image 509
Shashwat Kumar Avatar asked Sep 03 '25 03:09

Shashwat Kumar


1 Answers

From the point of view of the language, the behaviour of signed integer overflow is undefined. Which means anythign could happen - it can be negative, it can be unchanged, the program can crash or it can order pizza online.

What will most likely happen in practice depends on the processor architecture on which you're running - so you'd have to consult the platform specs to know.

But I'd guess you can't guarantee overflow to be negative. As a contrived example:

signed char c = 127;
c += 255;
std::cout << (int)c << '\n';

This happens to print 126 on x86. But again, it could actually do anything.

like image 126
Angew is no longer proud of SO Avatar answered Sep 04 '25 18:09

Angew is no longer proud of SO