Filipe Wolve
Filipe Wolve

Reputation: 347

Problems using the operator "+=" in batch file

Ok It's simple. I just want to add 1 to a number every time trought the use of += operator!

So i go in prompt just like this:

C:\Users\fsilveira>SET teste=000007

C:\Users\fsilveira>ECHO %teste%
000007

C:\Users\fsilveira>SET /A teste+=1
8
C:\Users\fsilveira>

Wow nice. Seems to be working just fine.

From the behaviour of the last one, if I use the same operator again, it should just add one to eight right? So I guess I will have 9? But here is what's happening:

C:\Users\fsilveira>SET teste=000008

C:\Users\fsilveira>ECHO %teste%
000008

C:\Users\fsilveira>SET /A teste+=1
1
C:\Users\fsilveira>

What? 8 + 1 is 1 ? o_O

When it comes to the number 8 it does not work how it should (or how I believe it's suppose to)

I'm going insane over here.

Please some one could help me and explain to me what's happening? I really dont know!

Regards, Filipe

Upvotes: 2

Views: 188

Answers (5)

RGuggisberg
RGuggisberg

Reputation: 4750

In response to

"number 7 doesn't have 5 leading zeros too.. but still works with the operator!"

You will only have trouble with the leading zeros for numbers > 7 because 0-7 Octal are the same as 0-7 Decimal!

Upvotes: 0

Endoro
Endoro

Reputation: 37569

You can avoid this by removing leadig zeros:

C:\>set teste=000008

C:\>echo %teste%
000008

C:\>for /f "tokens=1*delims=0" %i in ("$0%teste%") do @set teste=%j

C:\>set /a teste+=1
9

Upvotes: 1

Ebbe M. Pedersen
Ebbe M. Pedersen

Reputation: 7498

When prefixing with 0 it is intrepeated as an octal number. And 00008 is not a valid octal number. You can see the effect of this by the following:

C:\Users>SET teste=000020

C:\Users>ECHO %teste%
000020

C:\Users>SET /A teste+=1
17

where 00020 in octal is 16 in decimal.

Upvotes: 6

OpenAll
OpenAll

Reputation: 13

The leading zeros makes things complicated; I would have expected the '000007' not to have worked in that way - the bottom line is: the '000008'; or any '8' with leading zeros is being handled as a string. Example:

C:\Users\op>set f=foo

C:\Users\op>echo %f%

foo

C:\Users\op>set /a f+=1

1

Upvotes: 0

Ken White
Ken White

Reputation: 125718

The number 8 doesn't have 5 leading zeros. If you're doing math, use real numbers. :-)

This works fine on my machine in a command window in Win7 64-bit:

C:\Users\Ken>set /a teste=8
8
C:\Users\Ken>set /a teste+=1
9
C:\Users\Ken>set /a teste+=1
10
C:\Users\Ken>echo %test3%
10

C:\Users\Ken>

Upvotes: 1

Related Questions