开发者

How to avoid integer overflow?

开发者 https://www.devze.com 2023-01-03 16:30 出处:网络
In the following C+开发者_运维技巧+ code, 32767 + 1 = -32768. #include <iostream> int main(){

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?


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!


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


use 'unsigned short int' or 'long int'

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

精彩评论

暂无评论...
验证码 换一张
取 消