Reputation: 19
While I was making a program in C, I came across a problem. && is not evaluating the second operand, if first is false. I know this is known as short circuit behavior. But I want second operand to be executed, see the code below to know why?
while(a-- && b--){
//some statements
}
Please tell me different ways to accomplish my task. Thanks a lot!
Upvotes: 1
Views: 100
Reputation: 105992
If you want the execution of second operand whether a
is true
or false
then you can use comma operator. I think you need this:
while((b--, a--) && b) {...}
Upvotes: 1
Reputation: 320361
Since you are using postfix decrement, the whole thing can be rewritten as simply
while (a && b)
{
--a; --b;
//some statements
}
--a; --b;
(Whether you really need that last line is for you to decide.)
But if you really want to keep everything stuffed into that while
condition, there are different ways to achieve that as well. For example, you can replace &&
operator with &
operator as long as you remember to "normalize" the operands with !!
while(!!(a--) & !!(b--)){
//some statements
}
Upvotes: 2
Reputation: 2619
while(a && b){
a--; b--;
//some statements
}
// just after loop ends
a--; b--;
Upvotes: 1
Reputation: 39354
If you need decremented b
after the loop, why not just make it first to guarantee evaluation?
while (b-- && a--)
Of course, this might not work if a
and b
are more complicated than your question indicates.
Upvotes: 0
Reputation: 861
If a and b are small enough such that a*b doesn't overflow:
while( (a--) * (b--) )
{...}
If they can be large:
while( ((a--) ? 0xf : 0) & ((b--) ? 0xf : 0) )
{...}
Upvotes: 2