What does a for (;;) loop do [duplicate] - c++

This question already has answers here:
What for (;;) and while(); mean in C [duplicate]
(4 answers)
Closed 6 years ago.
In a c/c++ file I discovered a strange for loop
for (;;) {...}
I don't know if this runs once, infinetly or works in some other way
Source: https://git.kernel.org/cgit/linux/kernel/git/jejb/efitools.git/tree/PreLoader.c Line 87

The for(;;) loop will continue forever until some command inside the loop causes it to terminate.
Some examples of such commands would be "break", or "return"

In the Linux kernel, infinite loops are written like this, instead of the usual while(true) or while(1) in other projects. This is a matter of style.

That is an infinite loop. It's an ordinary for loop with no condition expression. It is equivalent to while(1). It is a bit odd to the eyes of nearly all C and C++ programmers, and should be avoided. I think people from a C/C++ background are more likely to prefer while(1) rather than for(;;).
K&R 2nd ed 3.5:
is an ``infinite'' loop, presumably to be broken by other means, such
as a break or return. Whether to use while or for is largely a matter
of personal preference.

It's an infinite loop, equivalent to while(true). When no termination condition is provided, the condition defaults to true.

Related

What is for(;;) loop in C++? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
My friend showed me this and I have no idea how it works and what it's called. Can someone explain to me how it loops the way it does? For example:
for(;;){
cout << "loop" << endl;
}
It will just keep looping the string forever. This kind of loop can be used for anything. How does this work?
According tho the language specification, empty condition in for iteration statament is equivalent to true condition.
6.5.3 The for statement
1 The for statement
for ( for-init-statement conditionopt; expressionopt) statement
is equivalent to
{
for-init-statement
while ( condition ) {
statement
expression ;
}
}
...
2 Either or both of the condition and the expression can be omitted. A missing condition makes the implied while clause equivalent to while(true).
So, the loop loops forever. That's all there is to it.
It loops infinitely as no initialization, conditional and increment values are passed in the parameters of the loop. A typical for loop takes parameters as follows: (<initialization>;<conditional>;<increment>)
This post explains it quite well in my opinion. See the answer by spex:
Why can the condition of a for-loop be left empty?
With the structure of the for loop being for(clause; expression-2; expression-3){}, when expression-2 is left out it is replaced with a nonzero constant. This is the part of the loop that determines whether it should keep looping or not. As a nonzero constant evaluates to true, it becomes an infinite loop.
That for loop essentially says the following three things (each separated by the semicolons in your for loop "header?"):
Don't initialize anything.
Don't break from the loop.
Perform no afterthoughts for each loop iteration.
Wikipedia's for loop page actually has a section about this.
As many have pointed out, it is equivalent to while (1).
When is it useful? Wherever you need an infinite loop such as:
A game loop - would be kinda useful to have the game, loop indefinitely until the user decides to quit the game.
OS scheduler - The scheduler needs to loop indefinitely, scheduling processes according to some algorithm until the OS stops
An intepreter - If you have ever programmed in python, you may have come across the interpreter which lets you type some command and then executes it. This is also implemented using a similar infinite loop
In all those examples, the common factor that leads to using an infinite loop is that the terminating condition is not known or the terminating condition is complex (game loops for example)

for (;;) is this an infinite loop? [duplicate]

This question already has answers here:
Is "for(;;)" faster than "while (true)"? If not, why do people use it?
(21 answers)
for loop missing initialization
(6 answers)
Closed 9 years ago.
Recently while going through a c++ tutorial I encountered a for loop that looked like this:
for (;;){
//Do stuff
}
Is this an infinite loop? Why would I use this rather that while(1)?
Yes, it's infinite. Traditionally, compilers would generate a warning when you use while(1), but not when you use for(;;). I don't know if this is still the case.
It's an infinite loop. More precisely, if the condition in a for is empty, it is considered true. As for while ( true ) vs. for (;;): historically for (;;) was the idiomatic form (used by Kernighan and Ritchie), perhaps partially because early C didn't have booleans. Using while ( 1 ) wouldn't pass code review anywhere I've worked. With booleans, while ( true ) definitely seems more intuitive than for (;;), but while ( 1 ) is confusing. But in pre-boolean times, everyone had a #define for true or TRUE or some such, so it's a weak argument. In the end, if you're an old C programmer, like me, who originally learned from Kernighan and Ritchie, you just instinctively use for (;;). Otherwise... it probably depends on where and from whom you learned C++.
Of course, when at work, you follow the house conventions, what ever they are.
Is this an infinite loop?
Yes.
Why would I use this rather that while(1)?
Because of (bad, IMO) taste. By the way, I would go for while (true), if I really had to create an infinite loop.

What is the feature to use for( ;; )? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is “for(;;)” faster than “while (TRUE)”? If not, why do people use it?
Found code with this for-loop.
What exactly feature to use it insted of while(true) for example? Is it uses less memory ?
for(;;) is functionally equivalent to while(true) but avoids a "conditional expression is constant" warning with some compilers (including MSVC's cl)
This construct has been popularized by Kernighan and Ritchie in their C Programming Language book (section 3.5)
The for statement
for (expr1; expr2; expr3)
statement
If expr1 or expr3 is omitted, it is simply dropped from the expansion. If the test, expr2, is not present, it is taken as permanently true, so
for (;;) {
...
}
is an "infinite" loop, presumably to be broken by other means, such as a break or return.
There is absolutely no difference between for(;;) and while(true).
while(true)
{
}
Is always what I've used and what I've seen others use for a loop that has to be broken manually.
Some compilers are giving you wrnings that this while loom MAY be incorrect. But it is not.
The assembly code generated for both is exactly the same. No diferences.
First, The use of loop depends on the requirement & based on that only we can decide when to use which one. Just check what #Luchian has asked, then you will come to know it.
Secondly, that clearly depends on the particular implementation of the interpreter/compiler of the specific language.
That said, theoretically, any sane implementation is likely to be able to implement one in terms of the other if it was faster so the difference should be negligible at most.

Is there anything wrong with using an empty for loop?

It was a little while since I last programmed and I have seem to forgotten if it's acceptable to use an empty "for loop" for creating an infinite loop?
for(;;)
Currently I use this method in a program to make it repeatedly ask the user to enter two numeric values one for each double variable in the program. The programs then calls a function and calculates a sum of these two pairs of numbers.
To terminate the program i have "if" statements that check if the user input value is zero, If the value is zero the program terminates using an "Return 0;" argument.
The program checks each user input value if it's zero directly after the value has been assigned to the variable.
So to the real question: Is this a correct way to make my program do what i described? Or is there a more/better/accepted way of programming this?
And secondly is there anything wrong with use the "Return 0" argument the way i did in this program?
If you thinks it's hard to understand what I'll wrote or meant please reply, and I will take more time to write everything.
What you're doing is perfectly fine, and an idiomatic way of writing and exiting an infinite loop.
I always use while(true) for infinite loops
I've seen this in a few places:
#define forever for(;;)
forever {
}
Not sure I'd recommend it though.
for(;;) as well as while(1) both are acceptable. These are just conditional loops provided by the language and you can use them to have a infinite running loop as per your requirement.
This is valid, you can go ahead with your code.
Yes, it's totally acceptable. Once you have an exit condition (break or return) in a loop you can make the loop "infinite" in the loop statement - you just move the exit condition from the loop statement into the loop body. If that makes the program more readable you of course can do that.
For an infinte loop for (;;) is fairly common practice. But if you do have a condition, such a non-zero user input, you could always have that check done in a while loop.
You can also use while loop with condition to repeatedly request user to input.
while (condition) {
...
}
Instead of IF block to validation you can use the .
What you describe will work fine, but it is worth mentioning that certain strict coding standards (i.e. MISRA) would disapprove of using a return before the end of a function.
If your code is subject to such standards then you could use do-while loop with a suitable exit condition instead:
do {
// get userinput
if (userinput != '0')
{
// do stuff
}
} while (userinput != '0');

Infinite loops - top or bottom? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
In the spirit of questions like Do your loops test at the top or bottom?:
Which style do you use for an infinite loop, and why?
while (true) { }
do { } while (true);
for (;;) { }
label: ... goto label;
while(true) {}
It seems to convey the meaning of the loop most effectively.
for (;;)
{
/* No warnings are generated about constant value in the loop conditional
plus it is easy to change when you realize you do need limits */
}
#define forever for(;;)
forever {
/*stuff*/
}
while(1)
{
//do it
}
That's how I roll.
I like to use the for(;;) approach because the MSVC++ compiler complains about while loop approach:
void main()
{
while(1) // test.cpp(5) : warning C4127: conditional expression is constant
{
}
for(;;)
{
}
}
I prefer while(1) or while(true) -- it's the clearest. do { } while(true) seems like needless obfuscation. Likewise, for(;;) can be confusing to people that have never seen it before, whereas while(true) is very intuitive. And there's absolutely no reason to do label: ... goto label;, it's just more confusing.
10 some l33t code
20 goto 10
I usually use for(;;) { } which I always think of as "for-ever".
Some languages offer a repeat { } construct which will natively loop forever. I find the for(;;) { } construct visually the most similar to this because it is so different from the normal for() construct. This is an important attribute for an infinite loop that while(1) { } doesn't really have.
Infinite tail-recursion ;)
It's somewhat compiler-dependant...
I use for (;;) in C-style languages and while true in languages that don't support that construct.
I learned the for (;;) method in K&R and it has always felt like idiomatic C to me.
Let the flaming begin...
If the loop is a true infinite loop (i.e. there is no break condition -- only an external event can terminate the thread's/process' execution), then I actually prefer the label and goto. Here's why:
First, the use of while, for, and do ... while, all imply that the loop might terminate. Even if the terminating condition is never achievable, the syntactical meaning of these constructs is that there is some termination condition.
Second, using a loop construct introduces an extra level of indentation. I hate indentation that's not necessary. It wastes valuable columnar real-estate.
Third, the only true infinite loop is the one that unconditionally jumps back to the beginning of the loop. Only goto fits that purpose exactly.
The truth is I don't really care that much about it. They all get the job done and most will result in the exact same assembly instructions anyway. However, the assembly that's generated will in all probability be an unconditional jump (if you're optimizer is worth a damn), which maps directly to which C construct, kids? That's right... your old friend goto.
When writing code for myself I use for(;;). Other people tend to be confused by its syntax and so for code that other people must see/use, I use while(true).
offtopic: if you think about what you are trying to express, you usually won't need an infinite loop.
for(;;);
Filler text.
for (;;) is what I usually see.
Infinite loops are a bad idea, but in practice that doesn't always hold up.
I prefer while(1) { } but make sure something within the loop can cause it to break out.
I usually use while() {}, but after learning that for(;;) {} isn't some sort of crazy invalid syntax, I'll be sure to use the more unique option.
Differentiates infinite loops from actual conditionals, you see.
I now prefer the "for (;;)" idiom because it seems to 'stick out' more. I used to use the "while (true)" idiom because I thought it expressed intent better, but I've switched over because I think the "for (;;)" idiom is well known enough to adequately express intent as well as I believe it's better by being more visible.
Kind of like how Stroustrup made the new casts in C++ purposefully ugly - so they stick out.