Is there a defined evaluation order for &= and |=?

[亡魂溺海] 提交于 2020-01-24 03:39:24

问题


If you have a C function which returns an integer, you could write a statement like this:

MyInt &= MyFunc();

...where we're using the bitwise-AND assignment operator.

The question is: is MyFunc() guaranteed to be executed, even if MyInt equals zero?

Likwise, if we used the bitwise-OR assignment operator (|=), would MyFunc() always be executed, even if MyInt were set to all ones?

Put another way: is lazy evaluation permitted in C for bitwise operators?


回答1:


MyInt &= MyFunc();

is equivalent to:

MyInt = MyInt & MyFunc();

The language states that the & operator is not short-circuited. However, an optimiser could generate code not to call to the function if MyInt was zero and it was sure that the function had no side effects. I doubt any compilers acrtually do this, as the runtime test probably makes it a pessimisation.




回答2:


No. Bitwise operators are not short-circuited. MyFunc() execution is guaranteed regardless of the value of MyInt.



来源:https://stackoverflow.com/questions/1354138/is-there-a-defined-evaluation-order-for-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!