Original message from prad <[EMAIL PROTECTED]>: 

> suppose that you have 2 conditions A and B where B take a lot of effort to 
> determine (eg looking for a string match in a huge file). 
> 
> either A or B needs to be true before you can execute 'this'. 
> 
> the 2 if statements below are equivalent i think: 
> 
> if A or B: 
> do this 
> 
> if A: 
> do this 
> elseif B: 
> do this 
> 
> now, do they work the same way? 
> 

Both of these forms are equivalent only in languages which short-circuit 
Boolean expressions (not all language implement short-circuiting...).  C/C++ 
both support this feature.

What is the difference?  In languages which provide short-circuiting, 
sub-expressions within a complex expression will be evaluated left to right up 
to the point where the value of the overall expression is determined.  ie.  in 
(A or B), only one sub-expression needs to be true in order for the entire 
expression to be true.  So, if A is true, there is no need to evaluate 
sub-expression B to know the value of the overall expression.  However, if A is 
false, then B must be computed to determine the value of the overall 
expression.  Thus in C/C++, the two forms given above are equivalent.

Note that these sub-expressions within languages which support short-circuiting 
are evaluated from left to right.  Thus, the most expensive sub-expressions 
should be listed last -- placed as far right as possible.

OTOH without short-circuiting, both sub-expressions within (A or B) will be 
evaluated.  This does not match your second statement:

> if A: 
> do this 
> elseif B: 
> do this 

...which executes "do this;" based upon the truth of expression A.

You can consider short-circuiting of Boolean evaluation greedy, but it a 
feature which may also save clock cycles if the right-most sub-expressions are 
costly to evaluate.

j

Reply via email to