Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

left hand operand has no effect warning when using for loop in C


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

i < 10, j < 10

is allowed but probably isn't what was intended as it discards the result of the first expression and returns the result of j < 10 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.
(Collected) https://stackoverflow.com/a/17638765/5610655

If you want to test for multiple conditions use the logical AND operator && instead. Btw, comma-separated conditions run fine in my IDE.

Similar concepts have also been discussed previously. Have a look.
C++: Multiple exit conditions in for loop (multiple variables): AND -ed or OR -ed?
Are multiple conditions allowed in a for loop?

Here's a practical example. If you run the code given below, you'll see that it is outputting 10 times than 2 times

#include <stdio.h>
void main() 
    {
       int i,j;
       for (i = 0, j = 0; i < 2, j < 10; i++, j++) {
           printf("Hello, World!");
    }
}
--output----
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!

If you want both conditions to be effective, use AND(&&) operator instead of the comma-separated condition.

#include <stdio.h>
void main()
    {
        int i,j;
       for (i = 0, j = 0; i < 2 && j < 10; i++, j++) {
           printf("Hello, World!
");
    }
}
---output--
Hello, World!
Hello, World!

It's unnecessary to use AND separated multiple conditions, only one will condition will suffice. The condition with fewer iteration steps will only be executed and the loop will break.

#include <stdio.h>
void main()
    {
        int i,j;
       for (i = 0, j = 0; i < 2; i++, j++) {
           printf("Hello, World!
");
    }
}
---output--
Hello, World!
Hello, World!

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...