Integer overflow and order of operations

I recently had a problem with C ++ code that made me wonder if I had any misunderstanding of what the compiler would do with long operations ... Look at the following code:

#include <iostream>

int main() {
    int i = 1024, j = 1024, k = 1024, n = 3;
    long long l = 5;
    std::cout << i * j * k * n * l << std::endl;  // #1
    std::cout << ( i * j * k * n ) * l << std::endl; // #2
    std::cout << l * i * j * k * n << std::endl;  // #3
    return 0;
}

For me, the order in which the multiplications will be performed on any of these three lines will be undefined. However, here is what I would think (assuming int- 32b, long long- 64b, and both follow the IEEE rules):

  • In line # 2, the parenthesis is calculated first, using int-1073741824 as an overflow and storing. This intermediate result is promoted long longfor the last multiplication, and therefore the print result should be -5368709120.
  • # 1 # 3 "", undefined.

# 1 № 3 : , undefined, "" , long long . , 64b... , GCC 5.3.0 :

~/tmp$ g++-5 cast.cc
~/tmp$ ./a.out 
-5368709120
-5368709120
16106127360

16106127360 . , GCC , , .

- undefined, GCC , , ( undefined)?

+4
2

GCC .

  • . , .
  • .

, i * j * k * n * l = ((((i * j) * k) * n) * l), , .

+7

:

5.6 [expr.mul]

1 *,/% .

, a * b * c (a * b) * c. a * (b * c).

+3

Source: https://habr.com/ru/post/1624435/


All Articles