Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Extended KotD #1: _ANDALSO
#4
One aspect Steve didn't mention in the short-circuiting functionality of `_AndAlso` (and `_OrElse`), which can be used to simplify code that would otherwise require multiple `IF` levels:

Code: (Select All)
' Normal implementation
IF handle < -1 THEN
    IF _WIDTH(handle) >= 640 THEN ...
END IF

' This doesn't work
IF handle < -1 AND _WIDTH(handle) >= 640 THEN ...

' This does work
IF handle < -1 _AndAlso _WIDTH(handle) >= 640 THEN ...

The code here is checking that an image handle is valid, and if it is then it checks that the width of that image is at least 640. The point of the `handle < -1` is to avoid the 'invalid handle' error you will get if you pass an invalid handle to `_WIDTH()`.

In the regular case, this requires two levels of `IF`s. You might be tempted to simply use the `AND` example I gave, but that doesn't work for two reasons:

1. `AND` always evaluates both sides of the equation, so even if `handle < -1` gives false, the `_WIDTH(handle) >= 640` side is still evaluated, so the error happens anyway.
2. The evaluation order of the `AND` is not guaranteed. The compiler might simply evaluate `_WIDTH(handle) >= 640` first, completely defeating the purpose of the `handle < -1` check.

In comparison the single `_AndAlso` version does work as intended. `_AndAlso` has 'short circuiting' behavior, so if the left side evaluates to false then the right side is not evaluated _at all_, since the result will always be false anyway. Additionally the evaluation order is guaranteed, the left side is always evaluated first before the right side. The combination means that you can use `_AndAlso` to completely avoid the 'invalid handle' error while still only using a single `IF` statement.
Reply


Messages In This Thread
Extended KotD #1: _ANDALSO - by SMcNeill - 05-05-2024, 09:20 PM
RE: Extended KotD #1: _ANDALSO - by PhilOfPerth - 05-05-2024, 11:05 PM
RE: Extended KotD #1: _ANDALSO - by Dimster - 05-06-2024, 01:28 PM
RE: Extended KotD #1: _ANDALSO - by DSMan195276 - 05-06-2024, 06:39 PM
RE: Extended KotD #1: _ANDALSO - by dbox - 05-06-2024, 07:10 PM



Users browsing this thread: 1 Guest(s)