Can someone please explain why the following code results in total of 0? How does that add up to zero? I get the same result using different types such as long and long long. Thank you!
int num;
num = (256 * 256 * 256 * 256)-1; //-1 warning C4307: '*': integral constant overflow
cout << num << endl;
num = 256 * 256 * 256 * 256; //0 warning C4307: '*': integral constant overflow
cout << num << endl;
num = (256 * 256) * (256 * 256); //0 warning C4307: '*': integral constant overflow
cout << num << endl;
num = (256 * (256 * 256) * 256); //0 warning C4307: '*': integral constant overflow
cout << num << endl;
num = 256 * 256 * 256; // 16777216
cout << num << endl;
num = 256 * 256; //65536
cout << num << endl;
output:
-1
0
0
0
16777216
65536
Changing the type only affects: num = 256 * 256; num = num * 256 * 256; which adds up correctly.
long long num;
num = (256L * 256L * 256L * 256L)-1; //warning C4307: '*': integral constant overflow
cout << num << endl;
num = (256L * 256L * 256L * 256L); //warning C4307: '*': integral constant overflow
cout << num << endl;
num = (256 * 256) * (256 * 256); //warning C4307: '*': integral constant overflow
cout << num << endl;
num = (256 * (256 * 256) * 256); //warning C4307: '*': integral constant overflow
cout << num << endl;
num = 256 * 256 * 256;
cout << num << endl;
num = 256 * 256;
cout << num << endl;
num = num * 256 * 256;
cout << num << endl;
cout << sizeof(int) << endl;
cout << sizeof(long long) << endl;
output:
-1
0
0
0
16777216
65536
4294967296
sizeof(int) 4
sizeof(long long) 8
I suppose it has to do with the number of '*' multiplication operators. The math works with 3 or less.