185
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(;;)

See also: Which is faster: while(1) or while(2)?

Sid110307
  • 497
  • 2
  • 8
  • 22
Chris Cooper
  • 17,276
  • 9
  • 52
  • 70
  • 52
  • 1
    TRUE is 1, TRUE is a define of win32 afaik – smerlin Apr 09 '10 at 22:09
  • 5
    @smerlin: Could be. But what is it doing in a question that has no mention of Win32 whatsoever? – AnT stands with Russia Apr 09 '10 at 22:11
  • 1
    If this is C++, then use `true`. For C, use `TRUE`. That's all. – Steven Sudit Apr 09 '10 at 22:12
  • 3
    I was assuming TRUE to be defined to 1 for use as a pseudo-boolean value. – Chris Cooper Apr 09 '10 at 22:13
  • 21
    @Steven Sudit: What does `TRUE` have to do with C? The standard macro for true boolen result in C99 is still `true`. Where did the `TRUE` come from? – AnT stands with Russia Apr 09 '10 at 22:16
  • 5
    I personally find `for(;;)` to be the clearer construct. `while (true)` implies you're testing `true` every loop; obviously I know this is optimized away, but it's unnecessary code. – user229044 Apr 09 '10 at 22:18
  • 33
    That macro doesn't work, `#define EVER ;;` has been used in IOCCC though.. :) –  Apr 09 '10 at 22:27
  • I was just thinking the phrase "infinite loop" is kind of misleading, because really we don't mean infinite as there is still a condition that the loop breaks. Instead we mean it is a "loop that has complex conditions beyond the capability of the language's built-in constructs to support looping". It's just that the condition is not necessarily an expression, but might be an event or something of that sort. – AaronLS Apr 09 '10 at 22:45
  • 6
    Some header included by defines TRUE for the Windows BOOL type. That's probably where this comes from. It's really common in win32 programming. – sblom Apr 09 '10 at 23:33
  • 6
    just don't write for(;;); or you might get into some trouble – Samuel Carrijo Apr 10 '10 at 00:29
  • 18
    Isn't that macro for `#define while(TRUE)` declaring a macro that takes one argument called `TRUE` that is never used, therefore turning every single while loop in your program in to an infinite loop? – AshleysBrain Apr 10 '10 at 15:20
  • @Andrey: The standard macro in VS 6.0 is `TRUE`. – Steven Sudit Apr 11 '10 at 18:04
  • 9
    @Steven Sudit: No. There's no "standard macro in VS 6.0". Macro `TRUE` comes from header files associated with Windows API. It is not related to VS 6.0 in any way. And, as I said before, it has nothing to do with either C or C++. In C++ the "true" literal is just `true` (in VS 6.0 as well), in C89/90 there's no such thing at all, and in C99 it is macro `true`. This applies to all C/C++ compilers. – AnT stands with Russia Apr 11 '10 at 18:14
  • 2
    @AndreyT: I think you're trying to be pickier than is useful. VS 6.0 does come with the Windows SDK header files, which are included with StdAfx.h in a default project. This header has a `TRUE` #define. This #define has been around in the C Windows SDK for some time, predating the addition of `true` to the language, which is why I referred to it as being C++ but not C. Now that I've explained myself, I'm really not interested in quibbling past this point. – Steven Sudit Apr 11 '10 at 21:43
  • 4
    The point though: it's non-portable... – Matthieu M. Apr 12 '10 at 14:43
  • 2
    @Steven: There is no TRUE, simple as that. – GManNickG Apr 19 '10 at 17:48
  • 1
    @anon Just use `while(1)` then, although I am sure you were not [born an eagle](http://hyperboleandahalf.blogspot.com/2010/04/alot-is-better-than-you-at-everything.html). – Mateen Ulhaq Nov 20 '11 at 01:34
  • 1
    I see some people use 'goto' for infinite loop. Is 'goto' fastest? – Rick2047 Feb 14 '13 at 08:19
  • 2
    @GManNickG: you can't handle the TRUE. All non-Windows users, that is. – smci Mar 12 '13 at 09:16
  • 3
    So actually someone asked if `for (;;)` is ***faster*** (???) than `while (1)`. Faith in the programmer community lost, once again. –  Jun 30 '13 at 20:50
  • 3
    No one has pointed out: `for(;;)` is only 7 characters where `while(true)` is 11, even `while(1)` is 8. So from a Rabid Application Development standpoint we should all be using `for` clearly. Especially when `;;` makes use of valuable home-row real-estate normally squandered by QWERTY. –  Mar 31 '14 at 18:37
  • 4
    Actually `#define EVER ;;` has *never* been used in the IOCCC, at least not in a winning entry. When I was first learning C, I did use `#define EVER ;;`, or perhaps `#define EVER (;;)`. At the time, I thought it was very clever. I still think it's very clever; I just no longer thing that's a good thing. – Keith Thompson Jul 24 '14 at 18:47

21 Answers21

284
  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.
Ben Zotto
  • 70,108
  • 23
  • 141
  • 204
  • 244
    Intuitively, optimizing an infinite loop offers the potential for infinite speed-up. Good thing we don't program on intuition, then. :-) – Steven Sudit Apr 09 '10 at 22:13
  • 4
    It did matter, since some early compilers on some platforms did load a constant and made a conditional jump of it. Which on those days hardware, did matter. – peterchen Nov 21 '11 at 16:50
  • It matters to humans. [Why you shouldn't write while(2)](http://stackoverflow.com/a/24879856/830749) – Buge Jul 24 '14 at 21:16
  • 2
    I use for(;;) as while(true) will generate a warning about a constant conditional expression. – paulm Oct 03 '14 at 12:49
198

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
  • 243,077
  • 51
  • 345
  • 550
  • 83
    +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 Apr 09 '10 at 23:28
  • 19
    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 Apr 09 '10 at 23:48
  • 1
    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 Apr 10 '10 at 00:10
  • 3
    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 Apr 10 '10 at 00:14
  • @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 Apr 10 '10 at 01:03
  • 1
    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 Apr 10 '10 at 01:15
  • 7
    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 Apr 10 '10 at 01:38
  • @caf: good point. Code monkey see, code monkey do. Still, it's reassuring that jalf also sees advantages beyond just familiarity :-) – Steve Jessop Apr 10 '10 at 01:42
  • Cultural conventions are important though - they allow us to communicate more effectively. – caf Apr 10 '10 at 08:17
  • 7
    @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 Apr 10 '10 at 11:13
  • 4
    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 Apr 10 '10 at 11:14
  • 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 Apr 10 '10 at 15:43
  • 2
    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 { ... }` is equivalent to a while loop, there's a normal three-clause for loop, and finally `for i := range { ... }` 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 Apr 10 '10 at 18:46
  • 42
    Your compiler sucks if `while(true)` gives a warning. – Albert Jul 16 '10 at 03:43
  • @Albert: Microsoft Visual C++ developers seem to not share your opinion. – sharptooth Jan 25 '12 at 13:21
  • 1
    I don't quite know why, but to me `for(;;)` succinctly represents the quintessential badness of C (and C++, by inheritance). More so than the terrible treatment of arrays, even more so than the low regard for numerical programming, and even more so than the ~14 pages of summarized undefined behavior in the C standard, and much worse, the "we're so embarrassed by the huge amount of UB that exists in C++ that we won't even summarize it in an appendix" in the C++ standard. – David Hammen Jul 25 '14 at 23:09
  • My experience is that answers containing `for(;;)` get downvoted on Stack Overflow in cases where the same answer with `while(true)` would earn upvotes. – Dawood ibn Kareem Oct 04 '18 at 19:09
  • @DawoodibnKareem I suppose I'll have to go downvote some `while(true)` questions then... ;-) – Andrew Henle Jan 05 '21 at 19:40
58

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.

ta.speot.is
  • 26,914
  • 8
  • 68
  • 96
  • 42
    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.) –  Apr 09 '10 at 22:29
  • 40
    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." – Ben Zotto Apr 09 '10 at 22:32
  • Except for in VB, where true cast to an integer gives -1. – Kibbee Apr 10 '10 at 00:40
  • 26
    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 Jun 10 '10 at 12:21
  • 6
    @ShinTakezou much better to `#define LIFE 42` `while (LIFE)` :) – mr5 Jul 01 '13 at 15:04
  • 1
    well `while(true)` doesn't contain any number too. and for(;;) is not a keyword – RiaD Jul 26 '14 at 18:07
  • 1
    @RiaD Parse the phrase as *just one keyword*. – ta.speot.is Jul 26 '14 at 23:25
  • 1
    What about `for(0xEFAAAAAA)`? – Timmos Oct 10 '17 at 12:09
57

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
  • 297,451
  • 125
  • 333
  • 465
  • 10
    Yes, this is how you know that someone learned C from K&R, the way it should be learned. Whenever I see `while(TRUE)`, I suspect the programmer is a C newbie, or learned C from a For Dummies book. – Kristopher Johnson May 19 '10 at 22:00
  • 15
    I hear those newbies use [newfangled function definition style](http://stackoverflow.com/a/3092074/1011250) too. – Justin Oct 15 '14 at 18:47
  • 1
    IIRC, under Ritchie's original C compiler, `for(;;)` did generate less code than `while(1)`, and was therefore preferred (since they cared *a lot* about code size in those days). – Steve Summit Jan 13 '21 at 17:50
52

I prefer for (;;) because it's the most consistent in different C-like languages.

In C++ while (true) is fine, but in C you depend on a header to define true, yet TRUE is a commonly used macro too. If you use while (1) it's correct in C and C++, and JavaScript, but not Java or C#, which require the loop condition to be a boolean, such as while (true) or while (1 == 1). In PHP, keywords are case-insensitive but the language prefers the capitalization TRUE.

However, for (;;) is always completely correct in all of those languages.

Boann
  • 48,794
  • 16
  • 117
  • 146
  • 11
    Thanks for your answer! I think this is actually the first answer that shows an **objective** way that `for (;;)` is better. – Chris Cooper Sep 04 '12 at 00:30
  • 12
    I don't think I've ever need to write code that's correct in C, C++, JavaScript, Java, and C#. They're different languages. – Keith Thompson Jul 24 '14 at 18:43
  • 7
    @KeithThompson it's not about write code that is correct in many languages; i think it is about avoiding misinterpretation between developers with different backgrounds. – Mauro Sampietro Jul 25 '14 at 09:08
  • 9
    @sam: Both `while (1)` and `for (;;)` are common idioms for infinite loops in C. Anyone reading a C program who has trouble understanding either will likely have trouble with the rest of the code. It's not worthwhile to write C code that can be easily read by someone who doesn't know C. – Keith Thompson Jul 25 '14 at 14:51
  • 6
    @KeithThompson While a competent reader of C should definitely be familiar with both idioms, this could also be useful if the writer is a polyglot programmer. At my last job I worked in JS, ActionScript, and PHP on a daily basis, and unifying the way one writes code (where it makes sense to do so) can make programming faster and maintenance easier. – Ionoclast Brigham Jul 26 '14 at 06:26
  • 2
    This is a great reason to switch to `for`, as I've been burned by the very things in this post. –  Sep 11 '14 at 04:01
  • Update on "it's the most consistent in different C-like languages": in Kotlin, you can't write `for (;;)` - it's a syntax error - but instead the normal way you write an infinite loop in Kotlin is `while (true)`. Which is unfortunate, because I like using `for (;;)`. – k314159 Nov 07 '22 at 09:31
48

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
  • 278,309
  • 50
  • 514
  • 539
  • I doubt it's faster even in debug mode. – Steven Sudit Apr 09 '10 at 22:13
  • 115
    `for_infinite` is faster; 2 fewer characters to `puts`. – Dave Jarvis Apr 10 '10 at 06:48
  • It is technically true: Printing a shorter string is always faster than printing a longer string. There's no magic: `puts` must iterate from the string pointer's starting address through each memory location until it reaches the null character. More characters means more loop iterations, which means slower execution time. In practice, they'd have virtually identical run times. My comment was tongue-in-cheek. – Dave Jarvis Aug 31 '22 at 16:27
22

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
  • 333,147
  • 50
  • 533
  • 760
18

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
  • 25,504
  • 18
  • 62
  • 103
  • 25
    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 Apr 09 '10 at 22:40
  • 10
    Actually the purpose of macros in some languages is to invent new syntax. But regardless 'for (EVER)' in C/C++ is heinous. – Dan Olson Apr 09 '10 at 23:35
16

What about (if your language supports it):

start:
/* BLAH */
goto start;
bungle
  • 185
  • 2
  • 1
    ...which should generate identical output in the hands of any reasonable compiler. – Ben Zotto Apr 09 '10 at 23:25
  • 11
    +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 Apr 09 '10 at 23:59
  • 4
    I personally take a utilitarian view about goto. There are no raptors. The raptors are people. And it was people who started using goto to make spaghetti code. Also, assembled output for a loop looks pretty much just like this. The instruction sets for computers don't have concepts of "for" or "while", just "jump". – josaphatv Oct 13 '13 at 09:03
  • 1
    never ever ever use `goto` – lost_in_the_source Feb 02 '14 at 17:38
  • 2
    The really nice thing about `goto` is you don't have to worry about someone adding a `break` to make your loop less infinite. (unless you're already inside another `while` or `for` loop of course...) –  Mar 31 '14 at 18:45
14

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
  • 56,972
  • 11
  • 108
  • 137
  • 6
    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 Apr 09 '10 at 22:22
  • 3
    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. – David Espart Apr 09 '10 at 22:29
  • 9
    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. – ta.speot.is Apr 09 '10 at 22:39
  • 4
    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 Apr 09 '10 at 23:12
  • 5
    @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 Apr 10 '10 at 00:48
  • 5
    I agree that the idiomatic way ought to be the most readable. Which is why the idiomatic ways always need to be challenged and changed as languages and practices evolve. It took years for the terrible K&R "idiomatic" coding style to be replaced by the modern, more readable style, but it still happened. – Jason Williams Apr 10 '10 at 09:11
13
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
  • 1,022
  • 6
  • 7
  • 9
    what version of visual studio are you using? With 2008 I don't get this warning, even at warning level 4. – Jörgen Sigvardsson Dec 04 '10 at 22:31
  • 1
    @JörgenSigvardsson: The warning definitely fired in VS 2008 at warning level 4, though many library headers disable this warning or drop the level back down to 3, so you might not have seen it. In 2015, MSVC stopped generating the warning on certain trivial expressions, like `while (true)`, but still does it for other inputs like `while (42)`. Today, the documentation still suggests using `for (;;)` instead. https://learn.microsoft.com/en-us/cpp/error-messages/compiler-warnings/compiler-warning-level-4-c4127 – Adrian McCarthy Mar 21 '22 at 18:47
  • Darn, that was more than a decade ago! :D These days, it's either C with gcc or C#. C# doesn't complain about `while (true)` because of type system. In C, I try to use a valid condition in the loop. I often start out with a `while ()` if the condition isn't clear to me yet. – Jörgen Sigvardsson Sep 01 '23 at 06:48
11

Both should be same if your code is optimized by compiler. To explain what I mean by optimization, here is a sample code written in MSVC 10:

int x = 0;

while(true) // for(;;)
{
    x +=1;

    printf("%d", x);
}

If you build it in Debug mode (without any optimization (/Od)) disassembly shows the clear difference. There is extra instructions for the true condition inside while.

while(true)
00D313A5  mov         eax,1                //extra 
00D313AA  test        eax,eax              //extra
00D313AC  je          main+39h (0D313B9h)  //extra
    {
        x +=1;
00D313AE  mov         eax,dword ptr [x]  
00D313B1  add         eax,1  
00D313B4  mov         dword ptr [x],eax  
    printf("%d", x);
    ...
    }
00D313B7  jmp         main+25h (0D313A5h)  


for(;;)
    {
        x +=1;
00D213A5  mov         eax,dword ptr [x]  
00D213A8  add         eax,1  
00D213AB  mov         dword ptr [x],eax  
    printf("%d", x);
    ...
    }
00D213AE  jmp         main+25h (0D213A5h)  

However, if you build your code in Release mode (with default Maximize Speed (/O2)) you get same output for both. Both loops are reduced to one jump instruction.

for(;;)
    {
        x +=1;
01291010  inc         esi  

        printf("%d", x);
    ...
    }
0129101C  jmp         main+10h (1291010h)  

    while(true)
    {
        x +=1;
00311010  inc         esi  

        printf("%d", x);
    ...
    }
0031101C  jmp         main+10h (311010h)  

Whichever you will use does not matter for a decent compiler with speed optimization is on.

SylvanBlack
  • 129
  • 1
  • 4
  • This is actually a very good point! Without optimization even modern compilers will differ by several instructions. –  Mar 31 '14 at 18:56
11

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

James McLeod
  • 2,381
  • 1
  • 17
  • 19
10

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
  • 869
  • 7
  • 14
7

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
  • 88,407
  • 13
  • 85
  • 165
  • TRUE may not be #define TRUE 1, but any code base in which `while(TRUE)` evaluates as `while(0)` is not likely to benefit from `for(;;)`. – Justin Oct 15 '14 at 18:40
  • @Justin : I agree, it would be truly perverse, and it is not the strongest of the three arguments, but Bjarne Stoustrup uses a similar argument for avoiding the NULL macro in C++. `while(true)` should be preferred in any case. In C++ `bool` is reserved, and in C defined in C stdbool.h (making it less safe in C). `for(;;)` removes all doubt. – Clifford Oct 16 '14 at 20:02
5

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
  • 40,059
  • 14
  • 91
  • 135
  • 3
    How frequently do you see people told to prefer `++i` over `i++`? – Dennis Zickefoose Apr 10 '10 at 06:05
  • 8
    @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 Apr 10 '10 at 09:13
  • 6
    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 Apr 10 '10 at 11:52
  • @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 Apr 10 '10 at 12:32
  • 2
    @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 Apr 10 '10 at 12:39
  • @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 Apr 10 '10 at 13:39
  • 3
    @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 Apr 10 '10 at 15:10
  • 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 Apr 10 '10 at 15:16
  • @Mike Dunlavey: x43 speed-up? Try CUDA. – Clifford Apr 10 '10 at 19:57
  • @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 Apr 10 '10 at 20:00
  • 1
    @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 Apr 11 '10 at 14:03
  • With pre and post increment you **have** to care which one is used. The difference will change program function, not merely performance. If one of them "doesn't make sense" to you, then by all means avoid it. In that case, better switch to `foo = foo + 1;` and keep it in a separate statement. (And, to be safe, don't even think of using the trinary operator `?:`) Of course, this implies the preferred infinite loop form: `for(unsigned int i=0; i<0; i = i + 1);` –  Mar 31 '14 at 19:08
4
for(;;Sleep(50))
{
    // Lots of code
}

Is a clearer than:

while(true)
{
    // Lots of code
    Sleep(50);
}

Not that this applies if you aren't using Sleep().

Anatoliy Nikolaev
  • 22,370
  • 15
  • 69
  • 68
Armada
  • 718
  • 8
  • 19
4

The most important reason to use "for(;;)" is the fear of using "while(TRUE)" when you do exploratory programming. It's easier to control the amount of repetitions with "for", and also, easier to convert the "for" loop into an infinite.

For example, if you are constructing a recursive function, you can limit the amount of calls to the function before converting into an infinite loop.

    for(int i=0;i<1000;i++) recursiveFunction(oneParam);

When I'm sure of my function, then I convert it to an infinite loop:

    for(;;) recursiveFunction(oneParam);
4

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
  • 56,849
  • 17
  • 98
  • 154
  • 9
    If a compiler generates different code for those, it's time to ditch the compiler and get one from the last two decades. – GManNickG Apr 09 '10 at 22:21
  • 5
    "the execution time for the loops is not a big concern since these loops go on forever" -- that sounds so wrong to me.. – Blindy Apr 09 '10 at 22:29
  • 3
    @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 Apr 10 '10 at 15:37
3

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

nik
  • 3,688
  • 3
  • 21
  • 33
-1

As others have pointed out, it does not matter at all from a technical view. Some people think one is more readable than the other, and they have different opinions about which it is.

To me, that's basically just nitpicking, because any C programmer should be able to instantly recognize both while(1) and for(;;) as infinite loops.

Your define will not work. However, you CAN (but shouldn't) do this:

#define repeat for(;;)

int main(void)
{
    repeat {
        puts("Hello, World");
    }
}

But really, DON'T do things like that...

klutt
  • 30,332
  • 17
  • 55
  • 95