Functions AKA subprograms can be emulated using CALL, labels, SETLOCAL and ENDLOCAL.
An example of a function that determines arithmetic power:
@echo off call :power 2 4 echo %result% rem Prints 16, determined as 2 * 2 * 2 * 2 goto :eof rem __Function power______________________ rem Arguments: %1 and %2 :power setlocal set counter=%2 set interim_product=%1 :power_loop if %counter% gtr 1 ( set /a interim_product=interim_product * %1 set /a counter=counter - 1 goto :power_loop ) endlocal & set result=%interim_product% goto :eof
While the goto :eof at the end of the function is not really needed, it has to be there in the general case in which there is more than one function.
The variable into which the result should be stored can be specified on the calling line as follows:
@echo off call :sayhello result=world echo %result% exit /b :sayhello set %1=Hello %2 REM Set %1 to set the returning value exit /b
In the example above,
exit /b is used instead of
goto :eof to the same effect.
Also, remember that the equal sign is a way to separate parameters. Thus, the following items achieve the same:
call :sayhello result=world
call :sayhello result world
call :sayhello result,world
call :sayhello result;world
(See command-line arguments as a reminder)