The following code runs without giving any errors or warnings
#include
int main(){
int i, j;
int p = 0, q = 2;
for(i = 0, j = 0;
If you want to test both conditions, use the &&
operator.
What is happening in your code is related to how the comma operator ,
works.
Both i < p
and j < q
are evaluated, but only the result of the 2nd expression j < q
is checked by the for loop.
The condition
i < p, j < q
is allowed but probably isn't what was intended as it discards the result of the first expression and returns the result of j < q
only. The comma operator evaluates the expression on the left of the comma, discards it then evaluates the expression on the right and returns it.
If you want to test for multiple conditions use the logical AND operator &&
instead
i < p && j < q
for(i = 0, j = 0; i < p && j < q; i++, j++){
You can link them together with boolean and (&&)
for(i = 0, j = 0; (i < p) && (j < q); i++, j++){
The above won't print out anything in the loop because the (i < p)
condition fails immediately as i & p are both the same value (0).
Update: Your example is valid (but silly) C because if you start i=30 your loop will still execute 2 times, because the first result in a comma separated list is ignored.
Even I have read That Book by Mr Yashwant Kanetkar. It do says that only one condition is allowed in a for loop, however you can add multiple conditions in for loop by using logical operators to connect them. In other books that I have Read Along time Ago, said that only one condition is allowed.