在 while 循环内,最后一个逗号分隔的语句是否保证最后运行?

发布于 2024-09-29 19:12:52 字数 183 浏览 11 评论 0原文

考虑以下(简单的)代码段:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

你又不是我 2024-10-06 19:12:52

在一般情况下,C++ 允许以任何顺序计算逗号分隔的语句。

如果您指的是函数参数之间的逗号,那么它只是一个分隔符。

在您的例子中,您使用的是逗号运算符,它引入了一个序列点,保证逗号左侧操作数的所有副作用在评估右侧操作数之前已经稳定下来。

所以是的,它是明确定义的。

来自 ISO C++98 标准第 5.18/1 节:

从左到右计算由逗号分隔的一对表达式,并丢弃左侧表达式的值。左值到右值 (4.1)、数组到指针 (4.2) 和函数到指针 (4.3) 标准转换不适用于左表达式。除了临时变量的破坏 (12.2) 之外,左侧表达式的所有副作用 (1.9) 均在右侧表达式求值之前执行。类型和
结果的值是右操作数的类型和值;如果其右操作数是,则结果是左值。

In the general case, C++ allows comma separated statements to be evaluated in any order.

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:

A pair of expressions separated by a comma is evaluated left-to-right and the value of the left expression is discarded. The lvalue-to-rvalue (4.1), array-to-pointer (4.2), and function-to-pointer (4.3) standard conversions are not applied to the left expression. All side effects (1.9) of the left expression, except for the destruction of temporaries (12.2), are performed before the evaluation of the right expression. The type and
value of the result are the type and value of the right operand; the result is an lvalue if its right operand is.

银河中√捞星星 2024-10-06 19:12:52

是的。 , 运算符(除非重载!)引入了所谓的“序列点”,并且确实保证了从左到右的执行顺序。

Yes. The , operator (unless overloaded!) introduces a so-called sequence point and does indeed guarantee the order of execution from left to right.

望她远 2024-10-06 19:12:52

上面的评论已经解释了这一点。
滥用此方法的常见方式之一是

while(scanf("%d", &n), n){
    // do something
}

这将读取整数,直到我们读取零。

The above comments explained it.
And one of the common way of abusing this method is

while(scanf("%d", &n), n){
    // do something
}

This will read integer until we read zero.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文