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?
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?
はいあります:
if (var < 32767) var++;
ちなみに、定数をハードコードするのではなく、代わりにヘッダー ファイルnumeric_limits<short>::max()
で定義されたものを使用してください。<limits>
この機能を関数テンプレートにカプセル化できます。
template <class T>
void increment_without_wraparound(T& value) {
if (value < numeric_limits<T>::max())
value++;
}
次のように使用します。
short var = 32767;
increment_without_wraparound(var); // pick a shorter name!
#include <iostream>
int main(){
unsigned short var = 32767;
var++;
std::cout << var;
std::cin.get();
}
'unsignedshortint'または'longint'を使用します
#include <iostream>
int main(){
long int var = 32767;
var++;
std::cout << var;
std::cin.get();
}