Yolo-cell-hash
Yolo-cell-hash

Reputation: 75

Why does the equality operator not work on three conditions?

So I've been wanting on doing something very simple and ran into this, which I don't understand why:

@echo off
setlocal enabledelayedexpansion

set /a var1=10
set /a var2=10
set /a var3=10

:test1
if %var1%==%var2% (
    if %var2%==%var3% (
        echo This Works
        pause
    )
)

:test2
if %var1%==%var2%==%var3% (
    echo But this does not
    pause
)

In this case, the test1 label works perfectly but the test2 label doesn't work.

Can anyone help me understanding why?

Upvotes: 1

Views: 143

Answers (2)

aschipfl
aschipfl

Reputation: 34909

According to the help of the if command (type if /?), you can only compare two expressions but not three.

However, you could concatenate multiple comparisons:

if %var1% equ %var2% if %var2% equ %var3% (
    rem // Do something...
)

This is a short form of the following (which becomes particularly relevant as soon as you want to use else clauses):

if %var1% equ %var2% (
    if %var2% equ %var3% (
        rem // Do something...
    )
)

In the above I used the equ operator rather than == since you are comparing integers. If you want to compare strings, use ==, together with quotation (to avoid issues with empty strings and to protect special characters):

if "%var1%"=="%var2%" if "%var2%"=="%var3%" (
    rem // Do something...
)

Upvotes: 2

Alexander
Alexander

Reputation: 63271

No knowledge of batch, but I can share context from some other programming languages where this typically doesn't work.

This will likely parse as either:

  • (%var1% == %var2%) == %var3%, or
  • %var1% == (%var2% == %var3%).

In either case, one of the equalities between two variables is evaluated first, resulting in a false or true that will probably not be equal to the third variable (even if it does happen to, that's probably not what you want).

The solution is to use two seperate equalities, conjuncted with an AND operator, like %var1%==%var2% AND %var2%==%var3%

Upvotes: 1

Related Questions