views:

2221

answers:

16
for (;;) {
    //Something to be done repeatedly
}

I have seen this sort of thing used a lot, but I think it is rather strange... Wouldn't it be much clearer to say while (TRUE), or something along those lines?

I'm guessing that (as is the reason for many-a-programmer to resort to cryptic code) this is a tiny margin faster?

Why, and is it REALLY worth it? If so, why not just define it this way:

#DEFINE while(TRUE) for(;;)

EDIT: I'm assuming TRUE to be defined to 1 and FALSE to 0.

Thanks for your input everyone.

+67  A: 
  1. It's not faster.
  2. If you really care, compile with assembler output for your platform and look to see.
  3. It doesn't matter. This never matters. Write your infinite loops however you like.
quixoto
Intuitively, optimizing an infinite loop offers the potential for infinite speed-up. Good thing we don't program on intuition, then. :-)
Steven Sudit
I suppose you're right. I think I was getting caught up in "religious" debates about little things. Thanks for shaking my conscience loose. :D
Chris Cooper
@Steven LOL, that is interesting, but then consider that the only scenario where you actually reached that potential of infinite speed-up is when the loop never breaks and truly runs infinitely, which is likely either a bug, or if intended, will be an infinite wait before it reaches that potential.
AaronLS
I think he was making a joke. ;P
Chris Cooper
@Chris. In programming as in life, religious debates are only worth your time for things that really matter. This just isn't one of those things. As you can see, everyone has a pet way of writing an unending loop. Pick for yourself whatever makes you happiest for the little things, and then run your profiler on the code that matters. :)
quixoto
@Steven Sudit: A whole lot of Amiga software was developed by programming on Intuition. :)
bk1e
@bk1e: Different sort.
Steven Sudit
@AaronLS: Ah, but it would be an infinity with a higher cardinality! (Proof I went to college for nothing.)
Steven Sudit
+25  A: 

It's certainly not faster in any sane compiler. They will both be compiled into unconditional jumps. The for version is easier to type (as Neil said) and will be clear if you understand for loop syntax.

If you're curious, here is what gcc 4.4.1 gives me for x86. Both use the x86 JMP instruction.

void while_infinite()
{
    while(1)
    {
    puts("while");
    }
}

void for_infinite()
{
    for(;;)
    {
    puts("for");
    }
}

compiles to (in part):

.LC0:
.string "while"
.text
.globl while_infinite
    .type   while_infinite, @function
while_infinite:
    pushl   %ebp
    movl    %esp, %ebp
    subl    $24, %esp
.L2:
    movl    $.LC0, (%esp)
    call    puts
    jmp .L2
    .size   while_infinite, .-while_infinite
    .section    .rodata
.LC1:
    .string "for"
    .text
.globl for_infinite
    .type   for_infinite, @function
for_infinite:
    pushl   %ebp
    movl    %esp, %ebp
    subl    $24, %esp
.L5:
    movl    $.LC1, (%esp)
    call    puts
    jmp .L5
    .size   for_infinite, .-for_infinite
Matthew Flaschen
I doubt it's faster even in debug mode.
Steven Sudit
`for_infinite` is faster; 2 fewer characters to `puts`.
Dave Jarvis
+5  A: 

Not just a well-known pattern, but a standard idiom in C (and C++)

James McLeod
Yes, and I think some compilers warn on `while (true)` for the same reason they do on `if (true)`.
Steven Sudit
+18  A: 

Personally I use for (;;) because there aren't any numbers in it, it's just a keyword. I prefer it to while (true), while (1), while (42), while (!0) etc etc.

taspeotis
+1 for pointing out that it does not rely on magic numbers.
Steven Sudit
0, 1, and infinity are acceptable magic numbers, extending 0 and 1 to false and true isn't a loss. `true` is no more a magic number than `for` is a magic keyword or that `for(;;)` uses an implied magic infinity. (`while (42)` is indeed an abomination.)
Roger Pate
Tangent: one of my CS professors said "there are only three numbers in programming: 0, 1, and n. anything else is called a magic number."
quixoto
Agreed about 0 and 1 being acceptable magic numbers.
SamB
@quixoto: That's an excellent quote.
Chris Cooper
Except for in VB, where true cast to an integer gives -1.
Kibbee
`while (0x1001)` -- only `0` and `1`, no magic numbers here
Ben Voigt
while(42) is the coolest, produces no different result with respect to while(1) or while(true) or while(!0), and has _philosophical_ meaning. I suppose `for(;;)` is parsed faster than the others anyway
ShinTakezou
+2  A: 

The "forever" loop is popular in embedded systems as a background loop. Some people implement it as:

for (; ;)
{
 // Stuff done in background loop
}

And sometimes it is implemented as:

while (TRUE /* or use 1 */)
{
 // Stuff done in background loop
}

And yet another implementation is:

do
{
 // Stuff done in background loop
} while (1 /* or TRUE */);

An optimizing compiler should generate the same or similar assembly code for these fragments. One important note: the execution time for the loops is not a big concern since these loops go on forever, and more time is spent in the processing section.

Thomas Matthews
If a compiler generates different code for those, it's time to ditch the compiler and get one from the last two decades.
GMan
"the execution time for the loops is not a big concern since these loops go on forever" -- that sounds so wrong to me..
Blindy
@Blindy -- because it is wrong, what's of concern is the fraction of runtime spent processing looping logic, or the amount of looping logic per unit of useful work, neither of which are helped by the loop being infinite
Ben Voigt
+4  A: 

It's a matter of personal preference which way is faster. Personally, I am a touchtypist and never look at my keyboard, during programming -- I can touchtype all 104 keys on my keyboard.

I find if faster to type "while (TRUE)".

I mentally added some finger movement measurements and totalled them up. "for(;;)" has about 12 key-widths of movements back and fourth (between home keys and the keys, and between home keys and SHIFT key) "while (TRUE)" has about 14 key-widths of movements back and fourth.

However, I am vastly less error-prone when typing the latter. I mentally think in words at a time, so I find it faster to type things like "nIndex" than acronyms such as "nIdx" because I have to actually mentally spell out the lettering rather than speak it inside my mind and let my fingers auto-type the word (like riding a bicycle)

(My TypingTest.com benchmark = 136 WPM)

Mark Rejhon
lolwut? 15 char
Woot4Moo
I believe the OP was referring to runtime speed, not typing speed.
Roger Pate
I know. Just had to cover that base, too.
Mark Rejhon
s/personal preference/individual habit/
SamB
@SamB: Comment up-vote for s///. xDAnd yes, although I suggested it may be be due to runtime speed, I didn't know the actual answer. If this was it, I would have been happy.
Chris Cooper
+4  A: 

There's no difference in terms of the machine code that is generated.

However, just to buck the trend, I'd argue that the while(TRUE) form is much more readable and intuitive than for(;;), and that readability and clarity are much more important reasons for coding guidelines than any reasons I've heard for the for(;;) approach (I prefer to base my coding guidelines on solid reasoning and/or proof of effectiveness myself).

Jason Williams
That depends on your language. `for(;;)` is the traditional way to do this in C and C++. `while(true)` seems to be the convention in C# and Java and other languages. Your mileage may vary.
Billy ONeal
But someone that is not very familiar with C or C++ will read while(true) more easily and someone familiar with them will understand it as well, therefore is more readable.
despart
Yes, and somebody who is not very familiar with C or C++ might find STRING_SCAN_FORMATTED more readable than sscanf, but you don't see anyone putting #define STRING_SCAN_FORMATTED sscanf at the top of their code.
taspeotis
I'd say the idiomatic way of doing it *had better* be the most readable to your developer. Otherwise you really need better developers.
jalf
@despart: If somebody is not familiar enough with C++ to recognize that idiom for what it is, then they need to stay the hell away from my codebase.
Billy ONeal
Jason Williams
+1  A: 

I've seen some people prefer it because they have a #define somewhere like this:

#define EVER ;;

Which allows them to write this:

for (EVER)
{
    /* blah */
}
rmeador
I've seen that too; but it is not a good reason for preferring it. As a maintainer, you'd still have to check the macro definition to be certain that it did what you'd expect, whereas the original code was clear enough. The RTOS VxWorks has a macro `FOREVER` defined `for(;;)`, but that is no better. IMO macros should not be used to 'invent' a new language.
Clifford
Actually the purpose of macros in some languages is to invent new syntax. But regardless 'for (EVER)' in C/C++ is heinous.
Dan Olson
U R AWESUM BRO.
M28
Some people do funny things, like if they like Pascal they say `#define BEGIN {` and `#define END }`. I've even seen `#define DONKEYS_FLY (0)` so they can say `if DONKEYS_FLY ...`. Who says software is dull?
Mike Dunlavey
Copied from my comment on the question, where I pointed out it was only used for humorous/obfuscation purposes. Do not do this in real code.
Roger Pate
In California I beleive you you have to #define for(;;) LIKE_FOREVER
Martin Beckett
+2  A: 

I cannot imagine that a worthwhile compiler would generate any different code. Even if it did, there would be no way of determining without testing the particular compiler which was more efficient.

However I suggest you prefer for(;;) for the following reasons:

  • a number of compilers I have used will generate a constant expression warning for while(true) with appropriate warning level settings.

  • in your example the macro TRUE may not be defined as you expect

  • there are many possible variants of the infinite while loop such as while(1), while(true), while(1==1) etc.; so for(;;) is likely to result in greater consistency.

Clifford
+27  A: 

I prefer for(;;) for two reasons.

One is that some compilers produce warnings on while(true) (something like "loop condition is constant"). Avoiding warnings is always a good thing to do.

Another is that I think for(;;) is clearer and more telling. I want an infinite loop. It literally has no condition, it depends on nothing. I just want it to continue forever, until I do something to break out of it.

Whereas with while(true), well, what's true got to do with anything? I'm not interested in looping until true becomes false, which is what this form literally says (loop while true is true). I just want to loop.

And no, there is absolutely no performance difference.

jalf
+1 for avoiding warnings. But as for clarity, I find while clearer than for in this context. I guess that aspect just comes down to personal preference.
Tim
Yep, preferance and habit. If you're not used to seeing `for(;;)`, it'll obviously look strange. But I'd recommend trying to get used to it because it *is* a common idiom, and you're going to run into it again. ;)
jalf
I'm sure I'll run into again, but that doesn't mean it's a good practice =P. I agree with Tim that "while" is more telling, because "for" is usually used when you want to do something a specifiably number of times. As Jalf said, "for(;;)" has NO condition. why is no condition the same as a new condition? If I said "do this under no condition", it means NEVER DO THIS. Anyway, that's just my take. =)
Chris Cooper
It has no condition: It is an unconditional loop. And I do want to do something a "specified number of times". That number is just infinity.How is `while` better? You usually use that *until* the condition changes. And that's never gonna happen.I don't care about whether 1==1, or 42>0 or TRUE evaluates to true. All of those are just roundabout ways of saying "keep doing this". All of them *could* be placed in a `while` loop to achieve the same thing. But when we already have a specific loop form for this, why jump through all those hoops?
jalf
@jalf: is there any circumstance under which you would use a `while(condition)` loop, given that `for(;condition;)` does the same thing? In defence of `while(true)`, it explicitly states "the continuation condition always holds", i.e. "always continue". `for(;;)` implicitly says the same thing because of a special language rule that omitting the condition means always continue. Logically it could just as easily have meant always break, but of course loop-zero-times is a lot less useful than loop-forever. Or not been allowed at all. So it's a "special idiom" whichever you use.
Steve Jessop
To declare my interest, I usually write `while(true)`, but I don't think either is any more clear or readable or simple than the other, since they are both utterly clear. What I *want* to write is `loop { ... }`, or maybe `{ ... ; continue; }`, but never mind. I'd be inclined to avoid anything which leads to statements like "I am doing this a number of times equal to infinity", because I have a degree in maths, and that's just painful ;-)
Steve Jessop
jalf's comment about it being idiomatic is really the answer here. It's commonly used for "infinite loop" simply because it *is* the commonly used way of writing "infinite loop" in C. There doesn't have to be a good reason for an idiom - it's just a self-reinforcing convention.
caf
@caf: good point. Code monkey see, code monkey do. Still, it's reassuring that jalf also sees advantages beyond just familiarity :-)
Steve Jessop
Cultural conventions are important though - they allow us to communicate more effectively.
caf
@Steve: I don't see why I'd *ever* use `for(;condition;)`. That is what a while loop is *for*. But like I said, with an infinite loop, I don't really want the compiler to compare *any* condition. Naively, with a `while` loop, it'd have to test `true` every iteration (obviously, not even the dumbest compiler would do that, but it's the principle that bothers me. It strikes me as overspecifying your code), while with a `for(;;)` you are literally saying "there is no condition to test. Just loop". I find it the closest equivalent to your imaginary `loop {...}`
jalf
But, just so we're clear, this isn't something I feel strongly about. I have absolutely no problem seeing `while(true)` in code I have to work with, and I think both are perfectly readable. I'm just explaining why *I* think `for(;;)` is preferable.
jalf
Fair enough. I just asked because you said "we already have a specific loop form for this", so I was wondering whether you're taking the same view as Go, that "for" is all we need. Evidently not :-)
Steve Jessop
@Steve: Ah, I see. The more I learn of Go, the sillier I think it becomes. If we're going to eliminate loops, I'd just as well go all the way and say "loops are just a special case of recursion". We could just remove them entirely. I'm happy to have both while and for loops. And in general, I use for loops when the condition can be pre-determined (either an infinite loop, or loop a set number of times), and while when we have a "weird"/unpredictable condition that should be tested every iteration.
jalf
They haven't actually removed anything other than do...while, just conflated it. All the "parameters" to `for` are optional, so in Go an infinite loop is `for { ... }`. `for <condition> { ... }` is equivalent to a while loop, there's a normal three-clause for loop, and finally `for i := range <sequence> { ... }` is a foreach loop. Makes sense, although I've only used Go a little, so it's still doing my head in that the same keyword is used for everything ;-)
Steve Jessop
Your compiler sucks if `while(true)` gives a warning.
Albert
+8  A: 

I personally prefer the for (;;) idiom (which will compile to the same code as while (TRUE).

Using while (TRUE) may be more readable in one sense, I've decided to use the for (;;) idiom because it stands out.

An infinite loop construct should be easily noticed or called out in code, and I personally think the for (;;) style does this a bit better than while (TRUE) or while (1).

Also, I recall that some compilers issue warnings when the controlling expression of a while loop is a constant. I don't think that happens too much, but just the potential for spurious warnings is enough for me to want to avoid it.

Michael Burr
good point about it standing out more. +1
jalf
+5  A: 

What about (if your language supports it):

start:
/* BLAH */
goto start;
bungle
...which should generate identical output in the hands of any reasonable compiler.
quixoto
+1 ! It doesn't ameliorate `goto`'s numerous disadvantages but, if the algorithm you're trying to implement comes from a flow-chart, this is the most direct translation.
Edmund
+13  A: 

Because of Dennis Ritchie

  • I started using for (;;) because that's the way Dennis Ritchie does it in K&R, and when learning a new language I always try to imitate the smart guys.

  • This is idiomatic C/C++. It's probably better in the long run to get used to it if you plan on doing much in the C/C++ space.

  • Your #define won't work, since the thing being #define'd has to look like a C identifier.

  • All modern compilers will generate the same code for the two constructs.

Mark Harrison
Kristopher Johnson
+1  A: 

All good answers - behavior should be exactly the same.

HOWEVER - Just suppose it DID make a difference. Suppose one of them took 3 more instructions per iteration.

Should you care?

ONLY if what you do inside the loop is almost nothing, which is almost never the case.

My point is, there is micro-optimization and macro-optimization. Micro-optimization is like "getting a haircut to lose weight".

Mike Dunlavey
How frequently do you see people told to prefer `++i` over `i++`?
Dennis Zickefoose
@Dennis Zickefoose: The difference between `++i` and `i++` can potentially be significant if `i` is an instance of a class rather than a built-in and the compiler does not apply the trivial optimisation. The advice is to acquire a habit so that it won't catch you out when it counts.
Clifford
The thing about `++i` vs `i++` is that it doesn't cost you anything to make the "optimization". True, in most cases it makes absolutely no difference, but they're equally easy to type, so why not prefer the potentially most efficient by default? And I suppose the same applies here. If one *was* a tiny bit faster than the other, why *not* go for the faster one? What would we lose by doing it? Both are fairly easy to read and type out.
jalf
@Clifford: @jalf: I am trying to lose weight :-), and I do get haircuts, but arguments of the form: "You would save a micro-cent so why not do it?" don't impress me much, because it only takes a micro-reason to ignore it, such as "The sun is shining, so why think about it?"
Mike Dunlavey
@Dennis Zickefoose: You're right. I see that a lot on SO, and Clifford's comment is right. In addition, there's something I **don't** see a lot on SO, and that is how to do macro-optimization, like a 43x speedup: http://stackoverflow.com/questions/926266/performance-optimization-strategies-of-last-resort/927773#927773. So I wonder about our priorities.
Mike Dunlavey
@Clifford: While I understand your point completely (and as a pilot, that kind of reasoning is essential), in programming I always have to get down to specifics. For example, in the few cases I've seen where swapping the `++` and the `i` made a significant change in performance bacause `i` was a class instance, it made a *much larger* change in performance to replace `i` by an integer. "Can't always do that" you say? Maybe, but we're getting really hypothetical here, and in any case, macro-optimization can be relied on to pinpoint the problem.
Mike Dunlavey
@Mike: Yeah, but that's an apples to oranges comparison. Getting a haircut takes actual time, and probably even money. I agree it is such a microoptimization that it doesn't really matter. But it also doesn't *cost* us anything. if I can choose to go left or right, and the distance is the same, the terrain is the same, *everything* is the same, except that the left path has some marginal microscopic benefit, why not go left? You're right, it's not an impressive argument. But when the cost is literally zero, I see no reason to prefer the less optimal route.
jalf
I wasn't really disagreeing with you. I agree that you still shouldn't care which is used, but consistency of style is important. If two options are equally readable, you might as well chose the style that saves you three clock cycles. If the sun is shining, or you feel `while(1)` is more descriptive than `for(;;)`, then use it, regardless of the lost clock cycles. Even if that segment of code proves problematic, it probably won't be because of the type of loop you chose. By similar logic, I always use `i++` in my own code because it makes more sense to me.
Dennis Zickefoose
@Mike Dunlavey: x43 speed-up? Try CUDA.
Clifford
@Dennis Zickefoose: For the record I can seldom bring myself to write ++i in any case ;-); just too ugly! And if you called a variable i and it was not a plain `int`, there are probably greater coding style issues!
Clifford
@Clifford: I'm in violent agreement. I'm also really boring because I haven't found a humorous way to point out how amazing it is that hardware engineers knock their brains out making the machines faster and cheaper, while we coders, rather than eliminating unnecessary cycles, say "Why bother? Just throw more hardware at it." I have a mental image of a finely-bred race horse lugging a 400-lb jockey, or circling the track 10 times when once would do, or taking major detours.
Mike Dunlavey
+4  A: 
while(true)

generates a warning with Visual Studio (condition is constant). Most places I've worked compile production builds with warnings as errors. So

for(;;)

is preferred.

Michael
A: 

I assume while(true) is more readable than for(;;) -- its look like programmer misses something in for loop :)

and who cares which one is faster if any

nik