For Loop

From LabVIEW Wiki
Jump to: navigation, search

How do I stop a for loop?

A for loop by definition executes the requisite number of times (N). If the number of iterations is not known then you have to use a while loop.

Is there some religious prohibition against the while loop that precludes its use? There are ugly, inelegant things you could do by putting a case statement in the for loop to avoid doing anything after some number of iterations but there is no reason to do this except to introduce wasteful, inefficient, useless code. Use a while loop, you will like it.

An underappreciated feature of while loops is their ability to index arrays or produce array outputs similar to for loops. To do this "enable indexing" on the wire coming into or out of the while loop. Likewise you can disable indexing on for loops to avoid the indexing feature.

Why doesn't my FOR loop return a value?

As a good programming rule in LabVIEW, NEVER output a value from a for loop with indexing disabled. When the loop does not execute (0 iteration) a non indexing output stays undefined and will hold any garbage left there by previous memory usage. This is because the wire output from the for loop has no code or data source to get the value from when the loop does not execute. Instead, use a shift register (SR) to output the value and at the left SR enter a default value for the case when the loop does not execute. When the for loop does not execute this default value of the left SR is passed to the right SR. Similarly passing a refnum through a for loop that never executes (0 iterations) destroys the reference. Either pass the reference using a SR as described above or wire around the loop. Note that while loops always execute at least once so the outputs are always defined.