次のコードを検討してください。
#include <iostream>
using namespace std;
int main() {
// the following is expected to not print 4000000000
// because the result of an expression with two `int`
// returns another `int` and the actual result
// doesn't fit into an `int`
cout << 2 * 2000000000 << endl; // prints -294967296
// as such the following produces the correct result
cout << 2 * 2000000000U << endl; // prints 4000000000
}
結果をさまざまな整数型にキャストして少し遊んだところ、奇妙な動作に出くわしました。
#include <iostream>
using namespace std;
int main() {
// unexpectedly this does print the correct result
cout << (unsigned int)(2 * 2000000000) << endl; // prints 4000000000
// this produces the same wrong result as the original statement
cout << (long long)(2 * 2000000000) << endl; // prints -294967296
}
次の両方のステートメントで正しい結果が得られないと予想しましたが、なぜ一方が成功し、もう一方が失敗したのでしょうか。