Trap sharing of VBS for next loop

Time:2022-5-20

When writing “QWERTY password: encryption and decryption” yesterday, in order to get a 26 letter string, I wrote such a for next loop:

Copy codeThe code is as follows:


‘Author: Demon
‘Website: http://demon.tw
‘Date: 2012/2/10
For i = 65 To (i + 25)
s = s & Chr(i)
Next
WScript.Echo s


After running, I found that there was no string output. I felt very strange, so I simply modified it:

Copy codeThe code is as follows:


‘Author: Demon
‘Website: http://demon.tw
‘Date: 2012/2/10
For i = 65 To (i + 25)
WScript.Echo Chr(i)
s = s & Chr(i)
Next
WScript.Echo s


There was still no output, indicating that the statement in the for next loop had not been executed at all, so he was puzzled. So he consulted the prophet evening news, and he soon found the trap:

Copy codeThe code is as follows:


‘Author: Demon
‘Website: http://demon.tw
‘Date: 2012/2/10
For i = 65 To (i + 25) Step -1
WScript.Echo Chr(i)
s = s & Chr(i)
Next
WScript.Echo s


This time, the seed has finally been output. I believe you, who are smart, must also find out where the trap is. The evaluation order of the for next loop is not from left to right. The expression (I + 25) has been evaluated before I = 65. At this time, the value of I is 0 by default, so the original loop is equivalent to:

Copy codeThe code is as follows:


‘Author: Demon
‘Website: http://demon.tw
‘Date: 2012/2/10
For i = 65 To 25
s = s & Chr(i)
Next
WScript.Echo s


Of course, there will be no output. Finally, I changed the program to this:

Copy codeThe code is as follows:


‘Author: Demon
‘Website: http://demon.tw
‘Date: 2012/2/10
For i = Asc(“A”) To Asc(“Z”)
s = s & Chr(i)
Next
WScript.Echo s


It’s straightforward and won’t encounter the for next trap.