Is there a reason this doesnt work? or am I just doing it wrong?
It does work, but not in the way you anticipated:
a < 10 , b < 6
evaluates a < 10
and then b < 6
but it's the result of b < 6
that gets returned. So your loop will only go to 5.
Comma oparator (wikipedia)
Let me explain how a for loop works:
You have three 'segments', all of which are optional:
initialisation
this part is run once before the loop starts.
condition
this part is evaluated before every iteration, if this condition
evaluates to false the loop exits.
increment
is executed after every iteration.
for ( initialisation ; condition ; increment ) {
/* body of the for loop */
}
You can achieve the same semantics with a while
loop:
initialisation;
while (condition) {
/* body of the for loop */
increment;
}
So for example:
for (;1;)
will never exit and for (;0;)
will never run.
To achieve the desired behaviour you could do:
//1-9, and values of "b" which are 1-5
int a, b;
for (a = 1, b = 1; a <= 9; ++a, (b <= 4 ? ++b : 0)) {
printf("a: %d\n", a);
printf("b: %d\n", b);
printf("\n");
}
But you are better off doing this inside the for loop:
int a, b;
// This reads much better
for (a = 1, b = 1; a <= 9; ++a) {
printf("a: %d\n", a);
printf("b: %d\n", b);
printf("\n");
if (b <= 4) {
++b;
}
}