I’m getting unexpected behaviour with break in a while loop. Basically, it isn’t breaking out of the while, or even out of that iteration, but returning control to an earlier point in the same iteration. I think it might have to do with nested if statements?
Outcome: break itself works fine. The issue is that it does not work the same while debugging. For some reason break in a debug doesn’t break out of the loop, but just reiterates. So the behaviour was weird and unexpected while stepping in debug, but worked fine when the code just ran.
Count is 1
Count is 2
Count is 3
Count is 4
Count is 5
Count is 6
Count is 7
Count is 8
Count is 9
Count is 10
This is the situation I have that’s failing, but it seems to work here.
count <-1while(count <100) {print(glue::glue("Count is {count}"))if ((count %%2) ==0) {print(glue::glue("{count} is an even number"))if (count ==10) {break() } } count <- count +1}
Count is 1
Count is 2
2 is an even number
Count is 3
Count is 4
4 is an even number
Count is 5
Count is 6
6 is an even number
Count is 7
Count is 8
8 is an even number
Count is 9
Count is 10
10 is an even number
Just making the while more complicated doesn’t change it. Still works as expected.
count <-1while(count <100) {print(glue::glue("Count is {count}"))if ((count %%2) ==0) {print(glue::glue("{count} is an even number"))if (count ==10) {print('10') }if (count ==10) {print('breaking')break() } }if ((count %%2) ==1) {print(glue::glue("{count} is an odd number")) } count <- count +1}
Count is 1
1 is an odd number
Count is 2
2 is an even number
Count is 3
3 is an odd number
Count is 4
4 is an even number
Count is 5
5 is an odd number
Count is 6
6 is an even number
Count is 7
7 is an odd number
Count is 8
8 is an even number
Count is 9
9 is an odd number
Count is 10
10 is an even number
[1] "10"
[1] "breaking"
But if I put those in a function, and step in with a debug, it doesn’t break, it keeps iterating. Just a quirk, I guess that I need to be aware of.