Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid integer overflow?

In the following C++ code, 32767 + 1 = -32768.

#include <iostream>
int main(){
short var = 32767;
var++;
std::cout << var;
std::cin.get();
}

Is there any way to just leave "var" as 32767, without errors?

like image 479
noryb009 Avatar asked Jun 14 '10 23:06

noryb009


People also ask

How do you avoid integer overflow?

Initialize variable c as long long data type. long long c = a * b; 2. Instead of changing the data types of a and b, we can multiply a and b with 1LL while initializing the value of c so that multiplication of a and b with long long 1 also results into long long and that value will be stored in long long c.

How do you handle integer overflow?

In languages where integer overflow can occur, you can reduce its likelihood by using larger integer types, like Java's long or C's long long int. If you need to store something even bigger, there are libraries built to handle arbitrarily large numbers.

How do you stop overflow multiplication?

Ideally the safest approach is to avoid signed integer overflow entirely. For example, instead of multiplying two signed integers, you can convert them to unsigned integers, multiply the unsigned values, then test whether the result is in signed range.


1 Answers

Yes, there is:

if (var < 32767) var++;

By the way, you shouldn't hardcode the constant, use numeric_limits<short>::max() defined in <limits> header file instead.

You can encapsulate this functionality in a function template:

template <class T>
void increment_without_wraparound(T& value) {
   if (value < numeric_limits<T>::max())
     value++;
}

and use it like:

short var = 32767;
increment_without_wraparound(var); // pick a shorter name!
like image 89
mmx Avatar answered Oct 22 '22 02:10

mmx