Arithmetic inside a for loop batch file

Environment variables need not be expanded to use in a SET /A statement. But FOR variables must be expanded.

Also, even if your computation worked, the ECHO would fail because percent expansion takes place when a statement is parsed, and the entire FOR construct is parsed at once. So the value of %x% would be the value as it existed before the loop is executed. To get the value that was set within the loop you should use delayed expansion.

Also, you should remove the space before the assignment operator. You are declaring a variable with a space in the name.

@echo off
setlocal enableDelayedExpansion
for %%A in (100 200 300 400 500) do (
  set n=%%A

  REM a FOR variable must be expanded
  set /a x=%%A/25

  REM an environment variable need not be expanded
  set /a y=n/25

  REM variables that were set within a block must be expanded using delayed expansion
  echo x=!x!, y=!y!

  REM another technique is to use CALL with doubled percents, but it is slower and less reliable
  call echo x=%%x%%, y=%%y%%
)

Tags:

Batch File

Cmd