folks,
I am adding a logic expression in the for loop and it is not behaving as I expected. Could you shine some light on me? Thanks very much.
The following code works fine
for (i=0;i<N;++i)
if (a[i] == 1){
....
}
and I tried to write it this way, it seems the for loop is fully skipped.
for (i=0;i<N && a[i]==1;++i){
....
}
What is wrong with the 2nd way?
The loop continues while the condition is true. Remember that a for-loop
for(A; B; C)can be replaced with [conceptually]:So, you have:
So, if at the first instance a[i] is not 1, then you never enter the loop, and just go to whatever comes after. It’s probably not what you wanted to do, which is why it’s not doing what you wanted… 😉