nor*_*009 7 c++ variables integer-overflow
在以下C++代码中,32767 + 1 = -32768.
#include <iostream>
int main(){
short var = 32767;
var++;
std::cout << var;
std::cin.get();
}
Run Code Online (Sandbox Code Playgroud)
有没有办法让"var"保持为32767,没有错误?
Meh*_*ari 30
就在这里:
if (var < 32767) var++;
Run Code Online (Sandbox Code Playgroud)
顺便说一句,你不应该硬编码常量,而是使用头文件中numeric_limits<short>::max()定义的<limits>.
您可以在功能模板中封装此功能:
template <class T>
void increment_without_wraparound(T& value) {
if (value < numeric_limits<T>::max())
value++;
}
Run Code Online (Sandbox Code Playgroud)
并使用它像:
short var = 32767;
increment_without_wraparound(var); // pick a shorter name!
Run Code Online (Sandbox Code Playgroud)