Goal
I need to execute a function adder
if a condition is met, and then use the return value of this function, still only if this condition is met.
What I tried
@echo off
:main
set _sum=5
if "T" == "T" (
call :adder 25 10
echo "25 + 10 = %_sum%"
)
goto eof
:adder
setlocal
set number1=%1
set number2=%2
endlocal & set /a _sum="%number1% + %number2%"
goto eof
:eof
Issue
This prints:
"25 + 10 = 5"
Additionally, when adding a echo "25 + 10 = %_sum%"
after the if
block, the output then becomes:
"25 + 10 = 5"
"25 + 10 = 35"
This seems to indicate that the entire if
block is evaluated when encountered, thus replacing the _sum
variable by the value it has before the execution of the if
block.
This is further verified by removing the @echo off
, the relevant output here is:
if "T" == "T" (
call :adder 25 10
echo "25 + 10 = 5"
)
Full output:
> set _sum=5
> if "T" == "T" (
call :adder 25 10
echo "25 + 10 = 5"
)
> setlocal
> set number1=25
> set number2=10
> endlocal & set /a _sum="25 + 10"
> goto eof
"25 + 10 = 5"
> echo "25 + 10 = 35"
"25 + 10 = 35"
> goto eof
Solution
The only solution I have for now is postponing the use of the return values to after the if
block. In practice, it may force me to use a second if-else
statement with the exact same conditions.
set _sum=5
if "T" == "T" (
call :adder 25 10
)
if "T" == "T" (
echo "25 + 10 = %_sum%"
)
Is there another solution to this problem?
EDIT
There is indeed another solution to this problem, called "Delayed Expansion". More about this in the question this one is a duplicate of.