the symbols & & and || acting weird into a for loop. I'll be happy to get full explanation. thanks | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

the symbols & & and || acting weird into a for loop. I'll be happy to get full explanation. thanks

in the code that linked, there are three for loops, and each one is acting a little different, but i can't explain the exact reason for that. https://code.sololearn.com/cGC79LKLpcpC/?ref=app https://code.sololearn.com/cGC79LKLpcpC/?ref=app

3rd Mar 2021, 2:29 PM
‎Mmk
‎Mmk - avatar
2 Answers
+ 3
There is a rule called short-circuiting for the || and && operator. For the && if the left hand side evaluates to false then the right hand side is not even evaluated because there is no need for it, the entire expression is going to be false. For the || if the left hand side evaluates to true then the right hand side is not even evaluated because there is no need for it, the entire expression is going to be true. In the 2nd for loop the short circuiting rule starts working after the 2nd iteration, the b++ is never executed because a will be true from that point on. In the 3rd for loop b++ is not executed only in the 1st iteration because only then is a == false. In the 2nd iteration a == true so b++ is executed again. This rule does not exist in user defined versions of the || and && operator (which is almost never) This rule is often used together with null pointer checks like: if( ptr && ptr->access() ) ... There is no need to worry about a crash when dereferencing the pointer because the right hand side won't be executed if ptr is null. https://en.wikipedia.org/wiki/Short-circuit_evaluation
3rd Mar 2021, 2:48 PM
Dennis
Dennis - avatar
0
thank you.
3rd Mar 2021, 4:09 PM
‎Mmk
‎Mmk - avatar