Re: do while loops with &&
Yes, if pX is checked for NULL in brackets first then it will be executed first, being an AND openration both conditions will be checked always.
But if you want to make it sure and remove compiler dependancies then you shold have do those check before using while as follows,
Code:
X *pX;
do
{
//.....
bool bX = (pX != NULL) ;
bX = bX && (pX->func() >2) ;
}while(bX)
Re: do while loops with &&
First of all you need to allocate memory to pX :) ..
And the code you wrote is best option to check for NULL first.
regards
Re: do while loops with &&
Thank you both for your quick response
However I still not sure,
Krishnaa: you say that the left side will be calulated first, however then you say that in order not to depend on compiler, are there any compilers that may calculate the right side before the left side
irs_b: when you say best option, is this the only option or is there might be compiler that will check the right side first?
Thanks again
Avi123
Re: do while loops with &&
When using && ...
Left-to-right evaluation is guaranteed and the second operand is
not evaluated if the first operand is false.
Re: do while loops with &&
Thanks Philip,
Are there any other operators where left to right order is not guaranteed?
Thanks
Avi123
Re: do while loops with &&
You can get the associativity of all operators below link
C++ operator precedence
Re: do while loops with &&
Quote:
Originally Posted by Philip Nicoletti
When using && ...
Left-to-right evaluation is guaranteed and the second operand is
not evaluated if the first operand is false.
Just to emphasize the point, this is guaranteed by the language, and is not compiler-dependent. Every compiler out there will conform on this point.
Mike
Re: do while loops with &&
Actually the built in "&&" and "||" operators will short circuit.
For &&, if the first is falst the second is not evaluated.
For ||, if the first ie true, the second is not evaluated.
However if you overload the operator then both are evaluated under all conditions (hence the recommendation to never overload these operators!)
Re: do while loops with &&
That type of check is extremely common in production code.
I've also seen it frequently abbreviated as:
Code:
Thing *ptr;
if(ptr && ptr->foo())
...
though some might argue that the form 'if(ptr)' is a poor coding standard.
Re: do while loops with &&
And as soon as someone writes
Code:
template<class RHS_TYPE>
bool Thing::operator &&(Thing const &lhs, RHS_TYPEconst&rhs);
It Immediately Breaks! :eek:
Re: do while loops with &&
But as your pointed out, it is not recommended to overload operator&& anyway....
Re: do while loops with &&
And I also tend to be paranoid...
Even if I don't overload, how can I guarantee 100% that some vendor will not change their implementation at some point and implement the overload.