短路评价和副作用 [英] Short circuit evaluation and side effects

查看:103
本文介绍了短路评价和副作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 because c evaluates to 0. 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 by canInitWithSomeValue(&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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆