In my last article, I had written about how easy it is to execute Ring code from within C/C++.
Today’s article takes a look at the “Loop” command. This command is very similar to “continue” in many languages such as C++, Java, Python. etc. It is used to skip the rest of the statements inside a loop.
Consider the Java code shown below:
When you execute this code, this is what you get:
What is interesting about the Ring language is that the “loop” command can optionally take an integer expression to apply the “continue” semantics to even enclosing outer loops!
Below is a Ring program to illustrate this idea. The image shows the Ring “Notepad”, an IDE that comes with Ring. The LHS contains the source code and the RHS shows the output.
By the way, I want to point out another uncommon feature of Ring, namely the ability to change the built-in language keywords. In the above example, I have renamed “loop” to “continue” to be in sync with other languages.
The code has two loops, one nested inside the other. “continue” (or “loop”) is followed by a variable, whose value is defined outside the loops. It can be either 1 or 2. In this case, it is initialized with 1. Because of this, “continue” applies to the innermost loop, the same behaviour as in other languages. You can check the output. It is worth noting that the “loop” command, when not followed by an integer expression, assumes a value of 1, and hence applies to the innermost loop.
What happens if I change the variable “count” to 2? Here is the code and the corresponding output:
This is interesting, isn’t it? It is as if we had another “continue” statement in the outer loop.
Of course, whether or not this is a good programming practice is beyond the scope of today’s discussion. I am sure there are pros and cons, and a good programmer uses every language construct judiciously.
Here is the Ring example source code.
Have a nice weekend!
Recent Comments