forcing evaluation in if()

xs0 xs0 at xs0.com
Fri Nov 17 13:22:39 PST 2006


Antonio wrote:

> It's true:  the "correct" way is not to put "process" into "decission 
> blocks".
> 
> But there is some cases where I prefer to do something like
> 
>    Recordset rd = new Recordset()
>    Recordset rd2 = new Recordset()
>    while( rd.Read() &&& rd2.Read() ) {
>      doSomething( rd, rd2 );
>    }
>    // at this point, the number of Read()'s MUST BE the same
>    // in rd and rd2
> 
> 
> it's equivalent to:
> 
>    RecordSet rd = new RecordSet()
>    RecordSet rd2 = new RecordSet()
> 
>    bool exists = rd.Read();
>    bool exists2 = rd2.Read();
>    while( exists && exists2 ) {
>      doSomething( rd, rd2 );
>      exists = rd.Read();
>      exists2 = rd2.Read();
>    }
> 
> 
> Ok... you say it could be wrote as
> 
>    while( rd.Read() & rd2.Read() ) {
> 
> But & is "bit" tester, not a Logic evaluator... We are talking about a 
> hight level programming language... we can use "invariants" 
> "preconditions" "postconditions" and.... SURPRISSE... I have to use a 
> "bit test" for "logic comparations"... no thanks..

Well, for what it's worth - in Java, & | and ^ are called both "Integer 
Bitwise Operators" when used on integers and "Boolean Logical 
Operators", when used on booleans. && and || are called "Conditional 
And/Or".

Anyhow, when used on bools & is effectively a completely normal AND 
operator, equivalent to your &&&, nothing low-level about it, at least 
IMHO :) The only thing I'd change was that instead of always converting 
to integer (like the current spec says), if both sides are of bool type, 
the result is also bool.

> Otherwhise... bit test could be "optimized" (if left side is 0, "&" 
> allways evaluates to 0).

I disagree.. a valid optimization never changes the meaning of code, so 
if the right side could have side-effects, it can't be optimized away 
(and if it doesn't have side effects, it doesn't matter anyway). Also 
note that short-circuit evaluation of && and || is not a matter of 
optimization, the two operators are defined to behave that way.


xs0



More information about the Digitalmars-d mailing list