In the screenshot below, you can see the difference between the classic For Loop and one with a Conditional Terminal.
Show the Conditional Terminal by right-clicking on the frame of the For Loop structure and selecting Conditional Terminal from the context menu.
When would you want to use the Conditional Terminal?A For Loop are commonly used to iterate over an array of items, either operating on the items or checking for some condition within the items is satisfied (for example searching for an element with a certain value).
Sometimes, you might want to stop iterating over the items (i.e., break out of the For Loop) if:
- your objective was satisfied -- e.g., you found the element (s) you were looking for), or
- an error occurred during an iteration and it doesn't make sense to iterate over the remaining items.
Example 1 - Doing work in a For Loop that can generate errorsIn LabVIEW versions <= 8.2, you might have implemented some code that looks like this:
This example, takes an array of file paths and deletes any files that are larger than some maximum file size. (Warning: you might want to be careful with such a VI, since it deletes files.)
You can see that, in the event an error occurs, the VI will not do any more work. It will just finish iterating over the array, passing the error through, before it exists.
Now, in LabVIEW 8.5, we might want to rewrite this example, by wiring the error cluster to the Conditional Terminal of the For Loop in order to stop it, in the event of an error.
The above code that uses the Conditional Terminal will finish sooner, in the event of an error, and is also much more readable.
Example 2 - Searching an array in a For LoopNow, let's look at different example where we want to search an array for an element. Here is what our code might look like in LabVIEW <= 8.2.
And, here's how we could improve the performance in LabVIEW 8.5, using the Conditional Terminal.
By using a Conditional Terminal to stop the search once we've found the element we're looking for, we can exit the loop early and save CPU cycles.
What do you think about this new feature?These are just a couple simple examples of how using the Conditional Terminal of the For Loop in LabVIEW 8.5 can improve the readability and performance of your code.
What other patterns of use have you identified? Are there any benefits or drawbacks that you can think of? I'm interested to know whether you've tried using this new feature and if you've had success with it, in improving your code.