Looking through some old company code, I came across a for loop that looks like this:
for (;;) { //Some stuff }
I tried Google but couldn't find any answers. Did I fall asleep in a programming class or is this an unusual loop?
For-loops are typically used when the number of iterations is known before entering the loop. For-loops can be thought of as shorthands for while-loops which increment and test a loop variable. The name for-loop comes from the word for, which is used as the keyword in many programming languages to introduce a for-loop.
Similar to a While loop, a For loop consists of three parts: the keyword For that starts the loop, the condition being tested, and the EndFor keyword that terminates the loop.
A Python for loop runs a block of code until the loop has iterated over every item in an iterable. For loops help you reduce repetition in your code because they let you execute the same operation multiple times.
A for
loop in java has the following structure -
for (initialization statement; condition check; update) loop body;
As you can see, there are four statements here -
true
.Basically this is how the execution follows - first, when the loop is entered for the first time, the initialization statement is executed once. Then the conditional check is executed to see if it evaluated to true. If it is, then the the loop body is executed, otherwise the loop execution is finished. After that, the Update statement(s) is(are) executed. Next, the conditional check is executed again, and if it evaluates to true, then again the loop body is executed, then update statement is executed, then again the conditional check....you get the picture.
Now about your for( ; ; )
syntax. It has no initialization statement, so nothing will be executed. Its conditional check statement is also empty, which means it evaluates to true after that the loop body is executed. Next, since the update statement is empty, nothing is executed. Then the conditional check is performed again which will again evaluates to true and then this whole process will again repeat.
So you see, this is basically an infinite loop which has no initialization statement, whose conditional check will always evaluates to true, and which has no update statement. This is equivalent to -
while(true) { ..... }
which is another popular loop construct in java.
When you use an infinite loop like this, it's important pay attention to the breaking condition as in most cases you can't let a loop to run indefinitely. To break out of these kinds of loops, you can use the break
statement. The structure is as follows -
if(some_condition_is_true) break; // This will cause execution to break out of its nearest loop
or
if(some_condition_is_false) break;
This is the same as:
while(true) { //Some Stuff }
Basically, an alternate syntax for an infinite loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With