Will the C / C ++ compiler optimize this if statement?

I have code similar to this one and it’s a little difficult for me to read:

// code1
if( (expensiveOperation1() && otherOperation() && foo()) 
     || (expensiveOperation2() && bar() && baz()) {
  // do something
}

I simply changed it to the following to make it more readable:

// code2
const bool expr1 = expensiveOperation1() && otherOperation() && foo();
const bool expr2 = expensiveOperation2() && bar() && baz();
if(expr1 || expr2){
   // one of the conditions met
}

But should I worry about efficiency now?

I mean that in code1, if the first conjunctive sentence is fulfilled, it will not even look at the second, because it is already clear that the statement will be true.

But in my more readable example, it is necessary to calculate both cond1, and cond2. Or will the compiler be smart enough to change mine code2to code1if expr2 is no longer in use?

+3
7

, , , - .

, , , :

// code3
inline bool combinedOp1()
{
    return expensiveOperation1() && otherOperation() && foo();
}

inline bool combinedOp2()
{
    return expensiveOperation2() && bar() && baz();
}

:

if (combinedOp1() || combinedOp2())
{
    // do something
}
+24

, ?

// code3
bool expr = expensiveOperation1() && otherOperation() && foo();
expr = expr || (expensiveOperation2() && bar() && baz());
if(expr){
   // one of the conditions met
}

, , , , .

+19

, && & || , . , .

, , , .

+4

" " ""! !

, , "show assembly output". GCC -S. , 100% , .

, , "therefromhere" , , (.. ).

asm, 5 . : C?

+2

, , . - , . (?) , gcc -S. - , , .

+1

.

, , , .

, , .

, .

0

, , cond2 (Operation2(), bar() baz()) (.. ). , , , .

, , , , Operation2(), , .

FWIW, if these functions are clean, you should probably reorder them so that bar () and baz () run before the expensive Operation2 () (and the same goes for ordering in cond1).

0
source

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


All Articles