Mircea M
Mircea M

Reputation: 520

Variable multiplication in batch file

I am trying to multiply two variables through a batch file. The code is:

SETLOCAL ENABLEDELAYEDEXPANSION
@ECHO OFF
SET /A res = 0
FOR /L %%i IN (1,1,2) DO (
    FOR /L %%j IN (1,1,3) DO (
        SET /A res = %%i * %%j 
        ECHO Multiplying %%i and %%j
        ECHO %res%
        )
    )

The problem is that I always get 0 as a result. Can anyone please tell me what I am doing wrong?

Here's the output:

Multiplying 1 and 1
0
Multiplying 1 and 2
0
Multiplying 1 and 3
0
Multiplying 2 and 1
0
Multiplying 2 and 2
0
Multiplying 2 and 3
0

Thank you!

Upvotes: 2

Views: 7981

Answers (2)

RJFalconer
RJFalconer

Reputation: 11682

You need to use ! to expand the variable due to your delayed expansion setting:

SETLOCAL ENABLEDELAYEDEXPANSION
@ECHO OFF
SET res = 0
FOR /L %%i IN (1,1,2) DO (
    FOR /L %%j IN (1,1,3) DO (
        SET /A res = %%i * %%j 
        ECHO Multiplying %%i and %%j
        ECHO !res!
    )
)

Upvotes: 1

Joey
Joey

Reputation: 354606

This is because you're outputting the result in the same block where you set it. Read up help set on delayed expansion. cmd expands %variables% when a command is parsed which is much earlier than when it's executed. As a side effect your %res% is replaced by zero.

You need

setlocal enabledelayedexpansion

at the start and then use !res! instead of %res%.

Side note: Ditch the spaces around the = in your set calls. They work as you expect when using them with /A but won't otherwise.

Upvotes: 2

Related Questions