Dose anyone know why dose it still work if the code is written like mine and how dose it affects the program ?
In John Hammond's video (see the link below) he passed the value %x% and %y% separated to the x and y string as different argument when he call function :add_one.
But, as you can see in my example, it will return exact the value of the x 1 and y 1 at the end, even I don't passed the value of %x% and %y% like in the video along with the string/characters/variable name.
Please explain me the difference, because from his explanation, I have understood that I have to pass the string and the value always to have a correct return, but as in my example, even I have only passed the string/character/variable name I still get the correct rutrn.
I am referring to this video from his channel https://www.youtube.com/watch?v=x-ri889-UDA&list=PL69BE3BF7D0BB69C4&index=27
Next I put the examples.
My example.
@echo off
goto :main
:add_one
setlocal
echo Running 'add_one'...
endlocal & set /a %~1=%~1 1 & set /a %~2=%~2 1
goto :eof
:main
setlocal
set /a x=1
set /a y=50
echo.
echo Created variable X and set it to %x%.
echo Created variable Y and set it to %y%.
echo.
call :add_one x y
echo.
echo The value of X is now %x%.
echo The value of Y is now %y%.
endlocal
goto :eof
The thing I have understood from the video that might be the only correct way for returning the passed in value.
@echo off
goto :main
:add_one
setlocal
echo Running 'add_one'...
endlocal & set /a %~1=%~2 1 & set /a %~3=%~4 1
goto :eof
:main
setlocal
set /a x=1
set /a y=50
echo.
echo Created variable X and set it to %x%.
echo Created variable Y and set it to %y%.
echo.
call :add_one x %x% y %y%
echo.
echo The value of X is now %x%.
echo The value of Y is now %y%.
endlocal
goto :eof
CodePudding user response:
tl;dr - set /a
is weird and you don't need percent signs when you're doing math.
This is a side effect of batch having been developed by multiple different teams over the course of decades. When batch first came out as command.com
, there wasn't an option for math at all and you'd have to do some weird stuff with other programs to get it to work. When the language was refreshed for Windows NT with cmd.exe
, multiple features were added, including the /a
flag that allowed for arithmetic with signed 32-bit integers.
For whatever reason, the team who added the /a
feature decided that you shouldn't need to wrap variables in percent signs in order to evaluate expressions, so both set /a var=%var% 1
and set /a var=var 1
are both valid (interestingly, so is set /a var =1
).
set /a
also differs from regular set
statements in that spaces are not significant to the variable name. Usually, having spaces in a statement like set var = 5
would result in a variable that has to be referenced as %var %
that would have a value of ' 5
'. However, set /a
allows whitespace, so set /a var = var 1
still increments %var%
by 1.