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?
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.
It is possible to use multiple variables and conditions in a for loop like in the example given below.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With