Will the C / C ++ compiler reorder for commutative operators (e.g.: +, *) to optimize constants

Will the second line of the following code

int bar;
int foo = bar * 3 * 5;

optimized for

int bar;
int foo = bar * 15;

Or even more:

int foo = 3 * bar * 5;

can be optimized?

The goal is to ask if I can just write

int foo = bar * 3 * 5;

instead

int foo = bar * (3 * 5);

to keep parentheses. (and get rid of the need to manually manipulate this constant ordering =>, and in many cases the constants of grouping with related variables are more meaningful, rather than grouping constants for optimization)

+4
source share
3 answers

, , , , .

, ; , .

5.1.2.3

[# 1] , .

[# 3] .

[# 13] 5 - , . , , - , . ()

, , , (, x / 5.0 x * 0.2 , x + x * y x * (1.0 + y)).

+7

, . g++ 4.9.2 -O2:

int calculate(int bar)     
{
    return bar*3*5;
}

:

movl    %edi, %eax        # copy argument into eax
sall    $4, %eax          # shift eax left 4 bits
subl    %edi, %eax        # subtract original value from eax
ret                       # return (with eax as result)

, . 15 :

int calculate(int bar)     
{
    return (bar<<4)-bar;
}
+3

. , , .

, , / .

- , , , , . , - .

, , , , , .

, 3.4, ", .

+2

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


All Articles