Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inside a while loop, is the last comma separated statement guaranteed to run last?

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?

like image 727
Felix Fung Avatar asked Nov 01 '10 19:11

Felix Fung


2 Answers

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.

like image 140
jamesdlin Avatar answered Sep 18 '22 16:09

jamesdlin


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.

like image 27
Timothy Leung Avatar answered Sep 19 '22 16:09

Timothy Leung