Discussion forum for all Windows batch related topics.
Moderator: DosItHelp
-
Jer
- Posts: 177
- Joined: 23 Nov 2014 17:13
- Location: California USA
#1
Post
by Jer » 26 Jul 2016 00:00
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
-
elzooilogico
- Posts: 128
- Joined: 23 May 2016 15:39
- Location: Spain
#2
Post
by elzooilogico » 26 Jul 2016 04:15
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
-
Aacini
- Expert
- Posts: 1886
- Joined: 06 Dec 2011 22:15
- Location: México City, México
-
Contact:
#3
Post
by Aacini » 26 Jul 2016 06:11
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
-
Squashman
- Expert
- Posts: 4472
- Joined: 23 Dec 2011 13:59
#4
Post
by Squashman » 26 Jul 2016 06:28
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.
-
Jer
- Posts: 177
- Joined: 23 Nov 2014 17:13
- Location: California USA
#5
Post
by Jer » 26 Jul 2016 10:03
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
-
foxidrive
- Expert
- Posts: 6031
- Joined: 10 Feb 2012 02:20
#6
Post
by foxidrive » 26 Jul 2016 22:23
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!