序列点和评估顺序
我正在阅读 K&R,在评估像 a[i]=i++
; 这样的表达式时,我遇到了这个关于行为不确定性的例子; 6.5.2 美元的 C99 规格说明了这一点
在上一个和下一个序列点之间,对象的存储值最多应通过表达式的求值修改一次。此外,应只读先前的值以确定要存储的值。
上面来自 K&R 的例子适用于第一个陈述。请解释一下它是如何在第二次失败的。
标准是否说明了在涉及序列点的情况下子表达式的求值顺序。例如。 a[i++] || b[i++]
。我知道这些是从左到右评估的,但是这是如何从上面的陈述中得出的,或者它是否在标准中的某处明确说明?
I was reading through K&R and i came across this example about uncertainty in behavior while evaluating expression like a[i]=i++
;
The C99 spec in $6.5.2 says that
Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.
The above example from K&R holds good on the first statement. Please explain how does it fail on the second.
Does standard says anything about the order of evaluation of sub-expressions in case of the sequence points being involved. Eg. a[i++] || b[i++]
. I know that these are evaluated from left to right but how can this be derived from the above statement or is it explicitly stated in the standard somewhere ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
标准是否规定了序列点情况下子表达式的求值顺序?
在条件运算符的情况下,求值顺序已明确定义
&&
以及||
这就是短路起作用的原因。它是由c99标准明确规定的。
参考: c99 标准
附件 J:J.1 未指定行为
进一步,
6.5.14 逻辑或运算符
以及逻辑 AND:
6.5.13 逻辑 AND 运算符
Does standard says anything about the order of evaluation of sub-expressions in case of the sequence points?
The order of evaluation is well defined in case of conditional operators
&&
as well as||
and that is the very reason short circuiting works.It is explicitly specified by the c99 standard.
Reference: c99 Standard
Annex J: J.1 Unspecified behavior
Further in,
6.5.14 Logical OR operator
As well as for logical AND:
6.5.13 Logical AND operator
对于问题的第一部分:
该句子适用于由表达式更改的对象,即
i
(和a[i]
)。因此,i
的先前值应专门用于确定i
的“新”值。但表达式“使用”它还确定要写入的数组元素。
背景是,否则会不清楚
i
表示i
在增量之前还是之后的值。For the first part of the question:
The sentence applies to objects being changed by the expression, i.e.
i
(anda[i]
). So, the prior value ofi
shall be used exclusively to determine the "new" value fori
.But the expression "uses" it also to determine the array element to be written to.
The background is that otherwise it would be unclear if
i
denotesi
's value before or after the increment.