Search code examples
c++overflow

Should I cast all variables to long long to avoid overflow or the leftmost variable is enough?


Consider this code

int a = 1e6, b = 1e6;
int c = a, d = a;

long long x = (long long) a * b * c * d; 

long long y = (long long) a * b * (long long) c * d; 

does the right hand expression get evaluated from left to right to guarantee no overflow?


Solution

  • For ensuring that all operands are long long, it's enough to simply cast the leftmost operand to long long.

    long long x = (long long) a * b * c * d;
    

    Multiplication is left-associative, meaning that a * b happens first at a syntactical level. The type of the sub-expression a * b is long long, and so (a * b) * c is also multiplication between long longs, etc. This guarantees you that the entire chain of multiplications is happening with more precision than int.

    However, the final result of your calculation is 1024 which requires at least an 81-bit signed integer to represent. long long is most likely not wide enough.

    Note on overflow safety

    Note that generally, it's possible that a * b * c * d overflows, even if all operands received double the width by being turned from int to long long. If this was addition, then it would be safe, assuming that long long has double the width of int.

    Note on code quality

    In general, it's probably better to use the same degree of precision everywhere, so that you (and future readers of your code) don't have to ask this question.