开发者

Efficiency - function call in a conditional statement

I开发者_开发技巧f 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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜