DEV Community

Kasey Speakman
Kasey Speakman

Posted on

3 2

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.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

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 :/

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay