set var=10
set /a var=%var%+10
echo %var%
The final value of var
is 20.
The second line is not working within a command block used for example on an IF condition or on a FOR loop as delayed expansion would be needed instead of standard environment variable expansion.
Here is another, better way working also in a command block:
set var=10
set /A var+=10
echo %var%
The command prompt environment supports with signed 32-bit integer values:
+
and +=
-
and -=
*
and *=
/
and /=
%
and %=
&
|
~
^
<<
>>
!
-
(
and )
The Windows command interpreter does not support 64-bit integer values or floating point values in arithmetic expressions.
Note: The operator %
must be written in a batch file as %%
to be interpreted as operator.
In a command prompt window executing the command line set /A Value=8 % 3
assigns the value 2
to environment variable Value
and additionally outputs 2
.
In a batch file must be written set /A Value=8 %% 3
to assign the value 2
to environment variable Value
and nothing is output respectively written to handle STDOUT (standard output). A line set /A Value=8 % 3
in a batch file would result in error message Missing operator on execution of the batch file.
The environment requires the switch /A
for arithmetic operations only, not for ordinary string variables.
Every string in the arithmetic expression after set /A
being whether a number nor an operator is automatically interpreted as name of an environment variable.
For that reason referencing the value of a variable with %variable%
or with !variable!
is not necessary when the variable name consists only of word characters (0-9A-Za-z_) with first character not being a digit which is especially helpful within a command block starting with (
and ending with a matching )
.
Numbers are converted from string to integer with C/C++ function strtol with base
being zero which means automatic base determination which can easily result in unexpected results.
Example:
set Divided=11
set Divisor=3
set /A Quotient=Divided / Divisor
set /A Remainder=Divided %% Divisor
echo %Divided% / %Divisor% = %Quotient%
echo %Divided% %% %Divisor% = %Remainder%
set HexValue1=0x14
set HexValue2=0x0A
set /A Result=(HexValue1 + HexValue2) * -3
echo (%HexValue1% + %HexValue2%) * -3 = (20 + 10) * -3 = %Result%
set /A Result%%=7
echo -90 %%= 7 = %Result%
set OctalValue=020
set DecimalValue=12
set /A Result=OctalValue - DecimalValue
echo %OctalValue% - %DecimalValue% = 16 - 12 = %Result%
The output of this example is:
11 / 3 = 3
11 % 3 = 2
(0x14 + 0x0A) * -3 = (20 + 10) * -3 = -90
-90 %= 7 = -6
020 - 12 = 16 - 12 = 4
Variables not defined on evaluation of the arithmetic expression are substituted with value 0.