9

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?

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
noryb009
  • 548
  • 2
  • 10
  • 20
  • Do you get whats going on here? You've hit the ceiling for an integer (short), so adding one more flips the signs to the maximum negative amount for an integer. – blu Jun 14 '10 at 23:47
  • If you want a different mode where integers don't automatically wrap around, it doesn't exist, sorry. – dmazzoni Jun 14 '10 at 23:48
  • 6
    This reminds me of why I [can't sleep](http://xkcd.com/571/). :-) – James McNellis Jun 14 '10 at 23:51
  • 2
    This is called [saturation arithmetic](http://en.wikipedia.org/wiki/Saturation_arithmetic). It can be highly illogical, so be warned. What's 32767+1-1? – MSalters Jun 15 '10 at 08:58

3 Answers3

31

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!
Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
0
#include <iostream> 
int main(){ 
unsigned short var = 32767; 
var++; 
std::cout << var; 
std::cin.get(); 
} 
Khaled Alshaya
  • 94,250
  • 39
  • 176
  • 234
-1

use 'unsigned short int' or 'long int'

#include <iostream>
int main(){
long int var = 32767;
var++;
std::cout << var;
std::cin.get();
}
technomage
  • 525
  • 4
  • 14