Consider your example and the output (except I made the initial value of x
to be 22):
int i=0;
int a=5;
int x=22;
for(i=0; i<5; x=(i++,a++))
{
printf("i=%d a=%d x=%d\n",i,a,x);
}
Prints:
i=0 a=5 x=22
i=1 a=6 x=5
i=2 a=7 x=6
i=3 a=8 x=7
i=4 a=9 x=8
Notice that x
has either the initial value of x prior to the loop or the previous value from the last trip through the loop.
Recall that any for
loop can be expressed as an equivelent while
loop.
The for
loop of:
for(exp 1; exp 2; exp 3){
expressions
}
Is equivalent to:
exp 1;
while(exp 2){
expressions
exp 3;
}
So your for
loop can be written as:
int i=0; // exp 1 from the for loop
int a=5;
int x=22;
while(i<5){ // exp 2
// loop body
printf("i=%d a=%d x=%d\n",i,a,x);
x=(i++,a++); // exp 3 from the for loop
}
Prints same output.
The fact that exp 3
is evaluated at the end of the loop (whether it is a for or while loop) is why x
has the previous value of x in the body of the loop.
The final thing to consider is the comma operator. The expression:
i=(a+=2, a+b)
^^^ evaluate a then add 2
^ comma operator in this case
^^ add b to a
^ store the final expression -- the RH of the comma operator --
into i