views:

223

answers:

3

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?

+21  A: 

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
Yes, that would work... Thank you!
noryb009
Well that was easy, LOL.
Kaleb Brasee
+1 for the Template implementation. Very sexy.
chaosTechnician
Nice work, Mehrdad. +1
Norman Ramsey
+1  A: 
#include <iostream> 
int main(){ 
unsigned short var = 32767; 
var++; 
std::cout << var; 
std::cin.get(); 
} 
AraK
This answers the question that was asked, but not, I suspect, the question that was intended.
jeffamaphone
A: 

use 'unsigned short int' or 'long int'

#include <iostream>
int main(){
long int var = 32767;
var++;
std::cout << var;
std::cin.get();
}
technomage
Then x = 32676; x++ will result in x == 32677, not 32676.
Wooble
OK, so how do you avoid the overflow on an unsigned 64 bit integer?
Lorenzo