在 while 循环内,最后一个逗号分隔的语句是否保证最后运行?
考虑以下(简单的)代码段:
while (i++, i <= 10) {
// some more code
}
在一般情况下,C++ 允许以任何顺序对逗号分隔的语句进行求值。在 while 循环的情况下,我们至少(根据规范)保证最后一个语句(用作循环的条件)最后被评估吗?
Consider the following (trivial) code segment:
while (i++, i <= 10) {
// some more code
}
In the general case, C++ allows comma separated statements to be evaluated in any order. In the case of a while loop, are we at least guaranteed (by the specification) that the last statement (which is used as the condition for the loop) be evaluated last?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您指的是函数参数之间的逗号,那么它只是一个分隔符。
在您的例子中,您使用的是逗号运算符,它引入了一个序列点,保证逗号左侧操作数的所有副作用在评估右侧操作数之前已经稳定下来。
所以是的,它是明确定义的。
来自 ISO C++98 标准第 5.18/1 节:
If you're referring to the commas between function arguments, that's just a separator.
In your case, you're using the comma operator, and that introduces a sequence point that guarantees that all side-effects from the comma's left operand have settled down before evaluating the right one.
So yes, it is well-defined.
From section 5.18/1 of the ISO C++98 standard:
是的。
,
运算符(除非重载!)引入了所谓的“序列点”,并且确实保证了从左到右的执行顺序。Yes. The
,
operator (unless overloaded!) introduces a so-called sequence point and does indeed guarantee the order of execution from left to right.上面的评论已经解释了这一点。
滥用此方法的常见方式之一是
这将读取整数,直到我们读取零。
The above comments explained it.
And one of the common way of abusing this method is
This will read integer until we read zero.