I tried the below, and it seems that ‘test’ results in wrong value. 2500*2500*2500 == 15625000000, why the below operations result in different outcome?
unsigned long long int test = 2500*2500*2500;
fprintf(stderr, "*************** test = %lld, %llu\n", test, test);
unsigned long long int test2 = 15625000000;
fprintf(stderr, "*************** test2 = %lld, %llu\n", test2, test2);
Result:
*************** test = -1554869184, 18446744072154682432
*************** test2 = 15625000000, 15625000000
2500 * 2500 * 2500is never promoted pastint, so the signed overflow that occurs (which is, by the way, UB) stops the correct calculation from being performed.To allow it, you must tell the compiler that your literals are of a particular type. There are two ways to do this:
By casting—casting a literal is generally handled at compile-time and has no runtime overhead:
Note that the cast is performed on the multiplicands individually. If the result of the operation were cast (e.g.
(unsigned long long int)(2500 * 2500 * 2500)) then the cast would be too late to preserve the data.By suffixing:
This is exactly as efficient at runtime as casting of literals is, but depending on usage may be easier or harder to read. Suffixing must be applied directly to a literal (it cannot be applied to the result of an operation, so
(2500 * 2500 * 2500)ULLis illegal.)