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?
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.
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With