Okay, I think I know what is going on.
I wrote this test script with no loops:
Code:
#include <stdio.h>
int main() {
int i,ii,c;
i=ii=c=0;
printf("\nStart:i=%d,ii=%d\n",i,ii);
c++;
if( i++ || ii++ ){
printf("%d:if:i=%d,ii=%d\n",c,i,ii);
} else {
printf("%d:else:i=%d,ii=%d\n",c,i,ii);
}
c++;
if( i++ && ii++ ){
printf("%d:if:i=%d,ii=%d\n",c,i,ii);
} else {
printf("%d:else:i=%d,ii=%d\n",c,i,ii);
}
i=ii=0;
printf("\nReStart:i=%d,ii=%d\n",i,ii);
c++;
if( i++ && ii++ ){
printf("%d:if:i=%d,ii=%d\n",c,i,ii);
} else {
printf("%d:else:i=%d,ii=%d\n",c,i,ii);
}
c++;
if( i++ || ii++ ){
printf("%d:if:i=%d,ii=%d\n",c,i,ii);
} else {
printf("%d:else:i=%d,ii=%d\n",c,i,ii);
}
}
When I run the code I get:
Start:i=0,ii=0
1:else:i=1,ii=1
2:if:i=2,ii=2
ReStart:i=0,ii=0
3:else:i=1,ii=0
4:if:i=2,ii=0
Because the output for 1 says "else" it wasn't "true" but both counters got incremented.
Because the output for 2 says "if" it was true and both got incremented.
But after the restart 3 says "else" just like 1 but only the first variable was incremented.
And 4 was true but still only the first variable was incremented.
So, when there is an && both sides of the and are getting evaluated and that is why both counters went up. That makes sense, but since the else is what printed that means neither side was true, right?
I seem to remember in the K&R that in something like "a=b++" would give the value of b before it was incremented to a, and then increment b, so since my counters are starting at 0 the expression is considered false and then it gets incremented.
So in my original problem that should mean I can ... what? Reverse it? So I should change all the i++ and ii++ to ++i and ++ii?
Let me try that.
Hmmmn. I added a new block:
Code:
i=ii=0;
printf("\nReReStart:i=%d,ii=%d\n",i,ii);
c++;
if( ++i || ++ii ){
printf("%d:if:i=%d,ii=%d\n",c,i,ii);
} else {
printf("%d:else:i=%d,ii=%d\n",c,i,ii);
}
c++;
if( ++i && ++ii ){
printf("%d:if:i=%d,ii=%d\n",c,i,ii);
} else {
printf("%d:else:i=%d,ii=%d\n",c,i,ii);
}
And got:
ReReStart:i=0,ii=0
5:if:i=1,ii=0
6:if:i=2,ii=1
So it is true both times but of course 5 doesn't increment ii because of the ||, which is fine.
So if I want to increment more than one counter in a for loop I should use ++varname and use && operators.
Is there a better way to do this?
Doing "++a && ++b && ++c" seems okay right?