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
242k56 gold badges401 silver badges316 bronze badges
asked Jun 14, 2010 at 23:43
noryb009
5582 gold badges10 silver badges20 bronze badges
-
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– blu2010年06月14日 23:47:14 +00:00Commented Jun 14, 2010 at 23:47
-
If you want a different mode where integers don't automatically wrap around, it doesn't exist, sorry.dmazzoni– dmazzoni2010年06月14日 23:48:01 +00:00Commented Jun 14, 2010 at 23:48
-
6This reminds me of why I can't sleep. :-)James McNellis– James McNellis2010年06月14日 23:51:11 +00:00Commented Jun 14, 2010 at 23:51
-
2This is called saturation arithmetic. It can be highly illogical, so be warned. What's 32767+1-1?MSalters– MSalters2010年06月15日 08:58:49 +00:00Commented Jun 15, 2010 at 8:58
3 Answers 3
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!
answered Jun 14, 2010 at 23:44
Mehrdad Afshari
424k93 gold badges864 silver badges796 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
#include <iostream>
int main(){
unsigned short var = 32767;
var++;
std::cout << var;
std::cin.get();
}
answered Jun 14, 2010 at 23:47
Khaled Alshaya
97.5k41 gold badges183 silver badges238 bronze badges
1 Comment
i_am_jorf
This answers the question that was asked, but not, I suspect, the question that was intended.
use 'unsigned short int' or 'long int'
#include <iostream>
int main(){
long int var = 32767;
var++;
std::cout << var;
std::cin.get();
}
answered Jun 14, 2010 at 23:53
technomage
5254 silver badges15 bronze badges
lang-cpp