What is the difference between for(;;) and while(1)? [duplicate] - c++

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Is “for(;;)” faster than “while (TRUE)”? If not, why do people use it?
I was wondering what is the difference between for(;;) and while(1) when both perform same function? Will there be any difference of speed of compilation

The difference with these is that many compilers will warn about while(true) ("constant expression used as loop expression"), while none I know of warn about for(;;).
They should generate the same code, though.

no functional difference at all, just a matter of taste.

With for, you can do this:
#define ever (; ;) // note the two happy faces? ;)
for ever { ... } // endless loop
Which is not possible with while.

Both will cause infinite loop unless
break is called explicitly.
Personally I prefer while(1), it's
more readable

No difference. I prefer the latter.

6 of one, 110 of the other.
The latter appears more concise.

No difference, unless you want to make use some kind counter later as below.
for (int i =0; i < 100; i++) {
// some code
}

Both are the same in C++. However, your post is tagged with c# and c++.
If you're using C#, you'll need to use while (true) {...}. Personally, I prefer the same in C++: numbers are used only when dealing with... well, numbers! When dealing with boolean values, true and false are used instead.

They both defines the exact same functional behavior and produce exactly the same IL code from C#.

I'm old-school, I still do the following:
#define TRUE 1
#define FALSE 0
while (TRUE) { /*--do something, mutley--* }

Related

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.

Any reason to replace while(condition) with for(;condition;) in C++?

Looks like
while( condition ) {
//do stuff
}
is completely equivalent to
for( ; condition; ) {
//do stuff
}
Is there any reason to use the latter instead of the former?
There's no good reason as far as I know. You're intentionally misleading people by using a for-loop that doesn't increment anything.
Update:
Based on the OP's comment to the question, I can speculate on how you might see such a construct in real code. I've seen (and used) this before:
lots::of::namespaces::container::iterator iter = foo.begin();
for (; iter != foo.end(); ++iter)
{
// do stuff
}
But that's as far as I'll go with leaving things out of a for-loop. Perhaps your project had a loop that looked like that at one time. If you add code that removes elements of a container in the middle of the loop, you likely have to control carefully how iter is incremented. That could lead to code that looks like this:
for (; iter != foo.end(); )
{
// do stuff
if (condition)
{
iter = foo.erase(iter);
}
else
{
++iter;
}
}
However, that's no excuse for not taking the five seconds needed to change it into a while-loop.
Some compilers warn about constant loop conditions:
while (true) { /* ... */ } /* Warning! */
for (;;) { /* ... */ } /* No warning */
In the specific case of an infinite loop, I might choose a for loop over a while loop for that reason. But if the condition is not empty, I don't really see any benefit. My guess as to why it appeared in the mentioned project is that the code somehow evolved through maintenance, but was written in a more conventional way originally.
No. No. No.
Even if there were a microscopic performance difference, you'd have to be an end-stage Jedi performance tuner to have it matter enough to care.
Is there any reason to use the latter
instead of the former?
A misguided effort to impress your colleagues that you know that those two forms are equivalent.
A foolish maneuver to ensure "job security" by making your code as confusing as possible so that no one will ever want to change it.
The "w" key on your keyboard is broken.
It started life as a for loop with initializers and incrementing condition, and when the logic changed, the developer was too busy to change it.
It's possible to compile
for(INIT; CONDITION; UPDATE)
{
BODY
}
into
{
INIT
while(CONDITION)
{
BODY
UPDATE
}
}
UPDATE: The seemingly redundant extra scope is to cage any variable definitions in INIT, i.e. from for(int i = 0; ...). Thanks!
It's basically just a reordering of the expressions. So there's no reason to prefer one over the other, for performance reasons. I would recommend while() if possible, since it's simpler. If a simpler construct expresses what you want to do, I think that's the one to use.
As far as I know the two statements are optimized by the compiler into the same assember code anyway.. so no, there's no reason to do so - just personal preference.
I think "while" and "for" loops are meant for different idioms. The idiom of using "while" is "do something, while certain conditions are true". The idiom for "for" is "iterate over a certain range of elements"...
Whenever I read a code, I expect these idioms (and I think I am not alone). When I see "for" I understand, that someone is iterating over the certain range and I do not go into details. When I see the for cycle, used for another idiom (not the one, I expect), I get confused and have to go into details.
Anyway, it is very subjective...
In this case, I personally prefer the first loop as it is easier to write and read.
But if I have a loop that needs to some post statement, I'd use for loop like this:
for (; i < 10; i += 2)
There might be small compiler-dependent differences on the assembly level, but ideally both should behave exactly the same, and the former is more readable. So no, no reson to use the latter version other than nonconformism.
Compile both and check the resulting disassembly, if they are the same (which they probably are). Choose the one you find most readable.
if you want to do something a limited amount of times, then "for" let's you specify the constraint without jumbling it in with the logic inside your loop.
Keeping readability aside for a small while, there is usually no performance difference between the different loops. At least there is no significant difference.
For desktop applications you can chose based on Readability criteria. Refer to the other posts - e.g. looking at for loop someone thinks the incrementor is declared within the loop.
It seems for web applications e.g. client side scripting there might be a difference.
Check this site: http://www.websiteoptimization.com/speed/10/10-2.html
Run your own experiments and go by the results else stick by readability rules.
I can see 2 reasons, none of which I'd consider:
Only have 1 loop construct, but then Kristo's objection stands
write "for (; EVER;)", but then prefer a LOOP_FOREVER macro if really want this.
There really is no difference in C-ish languages between a for (;cond;) loop and a while loop. Generally what I do in C-ish languages is start off writing the loop as a "for" and change it into a "while" if I end up with that form. It is kinda rare though, as you are always iterating through something, and C lets you put any code you want in that last area.
It would be different if C had real (pre-computed iteration) for loops.
You might want to use a do-while loop instead of a for loop so the code is processed at least once before conditions are checked and met (or not).
I used to write some pretty cryptic C/C++ code. Looking back, I would probably do this in a while loop:
ifstream f("file.txt");
char c;
for(f.get(c); !f.eof(); f.get(c)) {
// ...
}
I guess my point is that for loops are usually shorter but less readable, if they're not used in the traditional sense of looping over a range.
This question has been answered - the language has a more natural construct for expressing what you want - you should use it. For example, I can certainly write this:
for (bool b = condition(); b; b = !b) {
/* more code */
}
or:
while (condition()) {
/* more code */
break;
}
instead of the more conventional:
if (condition()) {
/* more code */
}
But why? C (and all languages) have idioms and most of them make rational sense in terms of expressivity and expectation of meaning. When you dick with the idiom, your mess with the sensibilities of the person who has to read your code.

for(;true;) different from while(true)?

If my understanding is correct, they do exactly the same thing. Why would anyone use for the "for" variant? Is it just taste?
Edit: I suppose I was also thinking of for (;;).
for (;;)
is often used to prevent a compiler warning:
while(1)
or
while(true)
usually throws a compiler warning about a conditional expression being constant (at least at the highest warning level).
Yes, it is just taste.
I've never seen for (;true;). I have seen for (;;), and the only difference seems to be one of taste. I've found that C programmers slightly prefer for (;;) over while (1), but it's still just preference.
Not an answer but a note: Sometimes remembering that for(;x;) is identical to while(x) (In other words, just saying "while" as I examine the center expression of an if conditional) helps me analyze nasty for statements...
For instance, it makes it obvious that the center expression is always evaluated at the beginning of the first pass of the loop, something you may forget, but is completely unambiguous when you look at it in the while() format.
Sometimes it also comes in handy to remember that
a;
while(b) {
...
c;
}
is almost (see comments) the same as
for(a;b;c) {
...
}
I know it's obvious, but being actively aware of this relationship really helps you to quickly convert between one form and the other to clarify confusing code.
Some compilers (with warnings turned all the way up) will complain that while(true) is a conditional statement that can never fail, whereas they are happy with for (;;).
For this reason I prefer the use of for (;;) as the infinite loop idiom, but don't think it is a big deal.
It's in case they plan to use a real for() loop later. If you see for(;true;), it's probably code meant to be debugged.
An optimizing compiler should generate the same assembly for both of them -- an infinite loop.
The compiler warning has already been discussed, so I'll approach it from a semantics stand-point. I use while(TRUE) rather than for(;;) because in my mind, while(TRUE) sounds like it makes more sense than for(;;). I read while(TRUE) as "while TRUE is always TRUE". Personally, this is an improvement in the readability of code.
So, Zeus forbid I don't document my code (this -NEVER- happens, of course) it stays just a little bit more readable than the alternative.
But, overall, this is such a nit-picky thing that it comes down to personal preference 99% of the time.

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.