短路评价和副作用

编程入门 行业动态 更新时间:2024-10-20 07:58:18
本文介绍了短路评价和副作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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.

更多推荐

短路评价和副作用

本文发布于:2023-11-14 00:34:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1585732.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:副作用   评价

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!