开发者

difference between 'or' logic in c

In linux using gcc when开发者_如何学运维 I write a loop like this

while(1 || 0)

It enters the loop but when I write the loop like this

while(0 || 1)

it doesn't enter the loop. What is the differrence?


There is no any difference. Execution should enter the loop in both expressions.


Or you might be typing like

while(0||1);

Won't help you if you put ; after while loop


There's no difference here. In this case. You're doing something else wrong.


But there's actually difference - in C/C++, there's Short-circuit evaluation . So, as this is not your real code, this could help you.

For example, if you have

while( f() || g() )
// ..

if f() return true, g() will never be executed, as the expression will be evaluated to true immediately. The same for &&:

while( f() && g() )
// ..

if f() return false, g() will never be executed, because the value of the expression will be false for sure (independent of what g() will return here.

Well, if f() returns true (for the last example), g() will be executed, to calculate the value of the expression. The same with ||, but then if f() returns false.


In both cases it run infinite loop...its perfectly working ... there is no defference between them...

i think you are putting ; at the end of second while loop.. so remove that and see


both code snippet have same behaviour. In both case condition will be true and will return infinite loop behaviour.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜