Page 1 of 1
Set /A and grouping with () question
Posted: 26 Jul 2016 00:00
by Jer
I am asking if it is possible to use set /a and grouping inside an if-block.
With the 2nd if-block, I get the error: ) was unexpected at this time.
My purpose is to reduce code. Set /a help does not give grouping examples.
Thanks.
Code: Select all
@Echo Off
setlocal EnableDelayedExpansion
Set "x=10"
Set "y=2"
rem the answer is 18
If 0 equ 0 (
Set /A x-=%y%-1
Set /A x*=2
echo not grouped test, x: !x!
)
Set "x=10"
If 0 equ 0 (
Set /A x=2*(!x!-(%y%-1))
echo grouped test, x: !x!
)
endlocal
Re: Set /A and grouping with () question
Posted: 26 Jul 2016 04:15
by elzooilogico
you need to escape the closing parentheses for the grouping, so they don't interfere with the
if block parentheses logic
becomes
output in my computer (win 8 ES-es)
not grouped test, x: 18
grouped test, x: 18
Re: Set /A and grouping with () question
Posted: 26 Jul 2016 06:11
by Aacini
It is simpler to just enclose both the variable and the expression in quotes:
Code: Select all
If 0 equ 0 (
Set /A "x=2*(!x!-(%y%-1))"
echo grouped test, x: !x!
)
Antonio
Re: Set /A and grouping with () question
Posted: 26 Jul 2016 06:28
by Squashman
Aacini wrote:It is simpler to just enclose both the variable and the expression in quotes:
Yep. Even says it in the HELP file.
Code: Select all
The /A switch specifies that the string to the right of the equal sign
is a numerical expression that is evaluated. The expression evaluator
is pretty simple and supports the following operations, in decreasing
order of precedence:
() - grouping
! ~ - - unary operators
* / % - arithmetic operators
+ - - arithmetic operators
<< >> - logical shift
& - bitwise and
^ - bitwise exclusive or
| - bitwise or
= *= /= %= += -= - assignment
&= ^= |= <<= >>=
, - expression separator
If you use any of the logical or modulus operators, you will need to
enclose the expression string in quotes.
Re: Set /A and grouping with () question
Posted: 26 Jul 2016 10:03
by Jer
Thankyou all for your explanations about how to code set/a and grouped arithmetic expressions,
and for pointing out that quotes around expressions are required and mentioned in HELP.
Because this thread helped me, I'm sure it will help someone else who, like me, frequently have to see to believe.
The quoted expression solution I will use from Aacini:
Jerry
Re: Set /A and grouping with () question
Posted: 26 Jul 2016 22:23
by foxidrive
Squashman wrote:Aacini wrote:It is simpler to just enclose both the variable and the expression in quotes:
Yep. Even says it in the HELP file.
Oi! Stop reading the cmd help files. You might start people doing that and we don't know what that will lead to!