Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>A common idiom is to use the <a href="http://en.wikipedia.org/wiki/Comma_operator" rel="noreferrer">comma operator</a> which evaluates both operands, and returns the second operand. Thus:</p> <pre><code>for(int i = 0; i != 5; ++i,++j) do_something(i,j); </code></pre> <h2>But is it really a comma operator?</h2> <p>Now having wrote that, a commenter suggested it was actually some special syntactic sugar in the for statement, and not a comma operator at all. I checked that in GCC as follows:</p> <pre><code>int i=0; int a=5; int x=0; for(i; i&lt;5; x=i++,a++){ printf("i=%d a=%d x=%d\n",i,a,x); } </code></pre> <p>I was expecting x to pick up the original value of a, so it should have displayed 5,6,7.. for x. What I got was this</p> <pre><code>i=0 a=5 x=0 i=1 a=6 x=0 i=2 a=7 x=1 i=3 a=8 x=2 i=4 a=9 x=3 </code></pre> <p>However, if I bracketed the expression to force the parser into really seeing a comma operator, I get this</p> <pre><code>int main(){ int i=0; int a=5; int x=0; for(i=0; i&lt;5; x=(i++,a++)){ printf("i=%d a=%d x=%d\n",i,a,x); } } i=0 a=5 x=0 i=1 a=6 x=5 i=2 a=7 x=6 i=3 a=8 x=7 i=4 a=9 x=8 </code></pre> <p>Initially I thought that this showed it wasn't behaving as a comma operator at all, but as it turns out, this is simply a precedence issue - the comma operator has the <a href="http://www.cppreference.com/wiki/operator_precedence" rel="noreferrer">lowest possible precedence</a>, so the expression x=i++,a++ is effectively parsed as (x=i++),a++</p> <p>Thanks for all the comments, it was an interesting learning experience, and I've been using C for many years!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload