2015-12-12 3:10 GMT+01:00 Robert Ramey
On 12/11/15 5:50 PM, Robert Ramey wrote: To belabor the point, consider this little program:
#include <iostream> #include <cstdint>
using namespace std;
int main(){ int8_t x = 100; int y = x * x; cout << y << endl;
uint32_t z1 = 100; int8_t z2 = -100; auto y2 = z1 * z2; cout << y2 << endl;
return 0; }
which prints out:
10000 4294957296
This is due to the application of the C++ type promotion rules.
Is it any reason that C++ drives people crazy?
While I do agree with your point of view, I do not agree with the choice of the example. I would say that the problem here comes from the fact that that an unsigned type is used for anything else but a bit-set. To fix it, and to avoid such problems in the future, one does not necessarily have to use a library, but simply apply the rule "never use unsigned to represent integer numbers, even the positive ones". And it would work for some time, until I start playing with bigger numbers: int main(){ int8_t x = 100; int y = x * x; std::cout << y << std::endl; int z1 = 1000000000; int z2 = 1000000000; auto y2 = z1 * z2; // overflow std::cout << y2 << std::endl; return 0; } And at this point I need safe<int> (or a BigInt). Regards, &rzej