DEV Community

Kasey Speakman
Kasey Speakman

Posted on

TIL Why AND should have two representations.

In most languages, the concept AND has two different representations. For example, in F# there is logical AND:

let awesome = good && great
Enter fullscreen mode Exit fullscreen mode

Then there is bitwise AND:

// this is pretty common when working with Flags
let hasRed = someColors &&& Color.Red = Color.Red
Enter fullscreen mode Exit fullscreen mode

But then there's VB, for which both concepts use the keyword And. So I implemented a feature in VB to clone an image. I had this code snippet.

    Public Shared Function CloneImage(ByVal sourceImage As Bitmap) As Bitmap
        If sourceImage.PixelFormat And PixelFormat.Indexed <> 0 Then
            Return CreateIndexedImage(sourceImage)
        Else
            Return CreateNonIndexedImage(sourceImage)
        End If
    End Function
Enter fullscreen mode Exit fullscreen mode

This code always calls CreateIndexedImage. And it took me a bit to figure out why. It was because the language sees the keyword And as the lowest priority operator and evaluates it last. It does that because it is only considering the priority of logical And. So the actual evaluation was something like (sourceImage.PixelFormat) And (PixelFormat.Indexed <> 0). VB coerces the type of PixelFormat to be truthy, and the second condition will always be true.

The fix was to add parenthesis

        If (sourceImage.PixelFormat And PixelFormat.Indexed) <> 0 Then
Enter fullscreen mode Exit fullscreen mode

But this could have been avoided by simply having a different operator between the two uses. Then each could have a different order of precedence.

Top comments (1)

Collapse
 
nektro profile image
Meghan (she/her) • Edited

Many languages use && for logical and & for bitwise

edit: Totally misread you point, sorry about that :/