Multiplication order

What does C ++ do in chain multiplication?

int a, b, c, d;
// set values
int m = a*b*c*d;
+4
source share
5 answers

the operator *has associativity from left to right :

int m = ((a * b) * c) * d;

While in mathematics this does not matter ( associative multiplication ), in the case of C and C ++ we may or may not have overflow depending on the order.

0 * INT_MAX * INT_MAX // 0
INT_MAX * INT_MAX * 0 // overflow

And things get even more complicated if we consider floating point types or operator overloading. See Comments @delnan and @melpomene .

+12
source

No special "order" is multiplied, as shown, from left to right.

int m = a * b * c * d;

/ /. . , , , .

+2

int m=a*b*c*d;

(a * b), c, d, :

int m=(((a*b)*c)*d);
+2

. ++, , , , , . *, , . (, , ..), , , . , .

As far as I understand, the standard allows this optimization, but I am far from a “language advocate,” so my best guess about the standard is not a statement that needs to be trusted (compared to my experience regarding what compilers actually do).

+1
source

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


All Articles