Pergunta

If I have a bit of code looking like this:

if(someInteger || somecomplexfunction() > 0) {
    // do something
}

Will the function be called if someInteger evaluates to true?

p.s. compiling with GCC with -O2

Foi útil?

Solução

No, it won't. Logical operators in C short circuit, so if the left hand side of an || is true, the right hand side won't evaluate (and thus the function won't execute, and no side effects that it might have will take effect). Likewise with &&, if the left hand side evaluates false, the right hand side won't get evaluated.

This is defined in the C standard and happens in any standards-compliant compiler regardless of compilation options.

While this sometimes leads to better performance, it's not an optimization that compilers choose to make, it's something that's ingrained into the semantics of C.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top