Reputation: 1316
I want to count from 1 to 10 but skip 5. This only works when I place incr at the start below while. Why? I thought incr after else will increase a to 2 3 4 etc then skip 5 and go onto 10. But it stops at 5 and never continues.
this works
set a 1
set b 10
while {$a < $b} {
incr a
if {$a == 5} {
continue
} else {
puts $a
}
}
this does not work
while {$a < $b} {
if {$a == 5} {
continue
} else {
puts $a
}
incr a
}
Upvotes: 1
Views: 200
Reputation: 40743
Think about the logic of the continue command: It skips the rest of the loop, and start from the beginning. When a == 5, the if statement is true, so you skip the rest of the loop, which also skip the incr
command. Going to the top of the loop, a is still 5, and you skip the rest of the loop again. In effect, you are running into an infinite loop. One way to fix it is not to use the continue command:
set a 1
set b 10
while {$a <= $b} {
if {$a != 5} {
puts $a
}
incr a
}
By the way, the first way did not quite working: it skips number 1 and starts with 2.
Upvotes: 4