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?

4
  • 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. Commented Jun 14, 2010 at 23:47
  • If you want a different mode where integers don't automatically wrap around, it doesn't exist, sorry. Commented Jun 14, 2010 at 23:48
  • 6
    This reminds me of why I can't sleep. :-) Commented Jun 14, 2010 at 23:51
  • 2
    This is called saturation arithmetic. It can be highly illogical, so be warned. What's 32767+1-1? Commented Jun 15, 2010 at 8:58

3 Answers 3

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!
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

This answers the question that was asked, but not, I suspect, the question that was intended.
-1

use 'unsigned short int' or 'long int'

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

2 Comments

Then x = 32676; x++ will result in x == 32677, not 32676.
OK, so how do you avoid the overflow on an unsigned 64 bit integer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.