Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are multiple conditions allowed in a for loop?

Tags:

c

for-loop

The following code runs without giving any errors or warnings:

#include <stdio.h>

int main(){
    int i, j;
    int p = 0, q = 2;
    for(i = 0, j = 0; i < p, j < q; i++, j++){
        printf("Hello, World!\n");
    }
    return 0;
}

However, the book Let Us C (Yashwant Kanetkar) says that only one expression is allowed in the test expression of a for loop (see page 115 of the book).

I am not sure of the standard. Are multiple expressions allowed in the test expression of a for loop?

I surely can join the two expressions, but I was dumbstruck when I found the above code on this website. Is this valid C code or not?

like image 566
Nikunj Banka Avatar asked Jul 14 '13 10:07

Nikunj Banka


People also ask

Can you have multiple conditions in a for loop in C?

for( printf(“a”) , printf(“b”) ; printf(“k”), printf(“l”), printf(“m”) ; printf(“y”), printf(“z”)); Therefore, one can use logical AND or logical OR to club multiple conditions leading to a single boolean result.

Can you have multiple conditions in a for loop Java?

It is possible to use multiple variables and conditions in a for loop like in the example given below.


2 Answers

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
like image 119
simonc Avatar answered Oct 15 '22 21:10

simonc


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.

like image 8
vogomatix Avatar answered Oct 15 '22 21:10

vogomatix