短路评价和副作用 [英] Short circuit evaluation and side effects
问题描述
OK,我有点不好意思问这个问题,但我只是想确保...
据了解,C使用短路评价布尔前pressions:
INT C = 0;
如果(C&安培;&安培; FUNC(C)){/ *什么... * /}
在这个例子中 FUNC(C)
不叫,因为 C
计算结果为 0
。但如何对更复杂的例子,其中比较副作用会改变变量被下一个比较?像这样的:
INT℃; / *这甚至不是初始化... * /
如果(canInitWithSomeValue(和C)及和C ==东西){} /*...*/
功能 canInitWithSomeValue
返回给定指针在成功的情况下真实的变化值。它是保证后续的比较(ç== SOMETHING
在这个例子中)使用值由设置canInitWithSomeValue(和C)
?
无论编译器优化多么沉重使用?
它是保证后续的对比(在本例C ==东西)使用值由canInitWithSomeValue设置?(和C)
块引用>是的。因为有一个序列点
的左侧和右侧的操作数的评价之间的
&放大器;&安培;
(逻辑与),||
(逻辑OR)和逗号操作符。例如,在EX pression* P ++ = 0&安培;!&安培; * Q ++!= 0
,子恩pression * P ++的所有副作用!= 0的任何企图访问q前完成。
块引用>
一个序列点定义在它被保证previous评估所有的副作用将已被执行的计算机程序的执行的任何点,并且还没有被执行无副作用从后续评估
块引用>OK, I'm a little embarassed to ask this question, but I just want to be sure...
It is known that C uses short circuit evaluation in boolean expressions:
int c = 0; if (c && func(c)) { /* whatever... */ }
In that example
func(c)
is not called becausec
evaluates to0
. But how about more sophisticated example where side effects of comparison would change the variable being compared next? Like this:int c; /* this is not even initialized... */ if (canInitWithSomeValue(&c) && c == SOMETHING) { /*...*/ }
Function
canInitWithSomeValue
returns true and changes value at given pointer in case of success. Is it guaranteed that subsequent comparisons (c == SOMETHING
in this example) uses value set bycanInitWithSomeValue(&c)
?No matter how heavy optimizations the compiler uses?
解决方案Is it guaranteed that subsequent comparisons (c == SOMETHING in this example) uses value set by canInitWithSomeValue(&c)?
Yes. Because there is a sequence point
Between evaluation of the left and right operands of the
&&
(logical AND),||
(logical OR), and comma operators. For example, in the expression*p++ != 0 && *q++ != 0
, all side effects of the sub-expression *p++ != 0 are completed before any attempt to access q.
A sequence point defines any point in a computer program's execution at which it is guaranteed that all side effects of previous evaluations will have been performed, and no side effects from subsequent evaluations have yet been performed.
这篇关于短路评价和副作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!