11.25 批處理 函數(shù)
詳情鏈接地址? ? https://www.xiaobuteach.com/dos/bat/function.html?from=bili
批處理 函數(shù)
批處理中函數(shù)是借助標(biāo)簽來實(shí)現(xiàn)。這里我們介紹函數(shù)定義、函數(shù)調(diào)用、函數(shù)參數(shù)、函數(shù)返回值。
1 函數(shù)定義
:函數(shù)名
函數(shù)體
goto:eof
1)冒號+函數(shù)名 本質(zhì)是定義標(biāo)簽,冒號后的名稱也就是函數(shù)名。
2)goto:eof 表示退出函數(shù)。
示例代碼
批處理文件內(nèi)容如下。
:sum
?echo 調(diào)用函數(shù)sum執(zhí)行求和. xiaobuteach.com
?set /a result = 0
?for /L %%i in ( 1 1 10) do (
? ?set /a result = result + %%i
?)
?echo 結(jié)果為:%result%
goto:eof
2 函數(shù)調(diào)用
通過call實(shí)現(xiàn)函數(shù)調(diào)用。
call :函數(shù)名
示例代碼
call :sum
完整代碼如下
@ echo off
echo 第1次調(diào)用sum
call :sum
echo/
echo/
echo 第2次調(diào)用sum
call :sum
pause
exit /B 0
:sum
?echo 調(diào)用函數(shù)sum執(zhí)行求和. xiaobuteach.com
?set /a result = 0
?for /L %%i in ( 1 1 10) do (
? ?set /a result = result + %%i
?)
?echo 結(jié)果為:%result%
goto:eof
代碼說明
1)exit /B 0:表示退出當(dāng)前程序,但不退出控制臺。
2)函數(shù)的定義通常放在文件的最后。
3)主程序的代碼最后通常會使用exit /B 0,否則最后會多執(zhí)行一次函數(shù)中的內(nèi)容。
運(yùn)行結(jié)果
