Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c - While with multiple conditions

Can somebody please explain why a while statement like

while (ch != '
' || ch != '' || ch != ' ') { ... } 

does not work as I expected?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

UPDATE: As per your other comment, your expression is wrong - it has nothing to do with "while" having multiple conditions.

ch != ' ' || ch != ' ' is ALWAYS true, no matter what the characters is.

If the character is NOT a space, the second condition is true so the OR is true.

If the character is a space, the first condition is true (since space is not newline) and the OR is true.

The correct way is ch != ' ' && ch != ' ' ...

OLD answer:

Under normal circumstances there's no problem whatsoever with the expression above (assuming you wanted to do just that).

The only issue with yours is that it can sometimes be less than optimal (e.g. if b and c never change throughout the loop, in which case you need to cache the value of b!=1 in a variable).

while with multiple conditions may have a problem in one case - if those multiple conditions actually have intended side effects.

That is due to lazy evaluation of || and && in C, so that if the first expression is true, the rest will NOT be evaluated and thus their side effects will not happen.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...