• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

infinite loop: test before execution

Bossie

New Member
Hi all,

is there a way to test (debug?) a loop to see if it doesn't go into an infinite loop?
Besides the obvious (make sure the logic in your algoritm is sound)...
The only way I found is to use 'stops' in your code (either by using the breakpoints or by using something like 'display a msgbox every 100th time you execute the loop')
Any other ideas?

Maybe there is a "preprogrammed debug procedure" to test loops?
If not, it would be an idea...
 
Hi Le Chat !

An infinite loop is just a missing logic !
So the better logic the better code, warming a couple of neurones …

To stop any loop, keep down ESC key until appears a popup window.
So safer this exit from loop, use DoEvents function within this loop.
Sometimes it may be ALT + ESC the better.

Read also the basics in VBA inner help from EnableCancelKey property
and from Now function to wait until a time for example …
 
There really can't be a failsafe as this is totally subjective i.e. the condition the coder is putting as terminating a loop and whether it will occur or not.

Use a finite loop as much as possible (For...Next) where you define the repetitions at the very beginning. Do...while loop might prove more susceptible to this.

You can always use Key combination CTRL+BREAK to interrupt code besides what Marc has suggested.

Test codes on smaller manageable samples where you can quickly suspect if some loop is running forever. With larger data-sets you will be left guessing until eventual thing happens.
 
Hi ,

The standard way to do this is to use a counter.

Even though you have a Do ... Loop Until , or a Do While ... Loop construct , within the loop increment a counter.

Based on your logic , if you think the loop should not be executed more than 70 times , use a test for whether the counter exceeds , say 700 ; if it exceeds this abnormally high threshold , exit the Do loop.

Outside the loop , print out the value of the counter ; if everything were to be normal , the counter value may be around 70 , but if the code execution had gone into an infinite loop , its value would be equal to the threshold value.

Narayan
 
…following on from Narayank991's suggestion, you could use
Debug.Assert counter<700
or some such, within the loop.
This will stop the code and put it into debug mode should the value of counter be greater or equal to 700.
 
Back
Top