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)?

23
  • 52
    What is TRUE??? Commented Apr 9, 2010 at 22:07
  • 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? Commented Apr 9, 2010 at 22:16
  • 34
    That macro doesn't work, #define EVER ;; has been used in IOCCC though.. :)
    – Roger Pate
    Commented Apr 9, 2010 at 22:27
  • 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? Commented Apr 10, 2010 at 15:20
  • 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. Commented Apr 11, 2010 at 18:14

21 Answers 21

287
  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.
4
  • 246
    Intuitively, optimizing an infinite loop offers the potential for infinite speed-up. Good thing we don't program on intuition, then. :-) Commented Apr 9, 2010 at 22:13
  • 5
    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
    Commented Nov 21, 2011 at 16:50
  • It matters to humans. Why you shouldn't write while(2)
    – Buge
    Commented Jul 24, 2014 at 21:16
  • 2
    I use for(;;) as while(true) will generate a warning about a constant conditional expression.
    – paulm
    Commented Oct 3, 2014 at 12:49
201

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.

18
  • 85
    +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
    Commented Apr 9, 2010 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. ;) Commented Apr 9, 2010 at 23:48
  • 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
    Commented Apr 10, 2010 at 1:38
  • 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 {...} Commented Apr 10, 2010 at 11:13
  • 45
    Your compiler sucks if while(true) gives a warning.
    – Albert
    Commented Jul 16, 2010 at 3:43
60

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.

8
  • 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.)
    – Roger Pate
    Commented Apr 9, 2010 at 22:29
  • 41
    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
    Commented Apr 9, 2010 at 22:32
  • 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 Commented Jun 10, 2010 at 12:21
  • 6
    @ShinTakezou much better to #define LIFE 42 while (LIFE) :)
    – mr5
    Commented Jul 1, 2013 at 15:04
  • 1
    well while(true) doesn't contain any number too. and for(;;) is not a keyword
    – RiaD
    Commented Jul 26, 2014 at 18:07
56

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.

3
  • 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. Commented May 19, 2010 at 22:00
  • 15
    I hear those newbies use newfangled function definition style too.
    – Justin
    Commented Oct 15, 2014 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). Commented Jan 13, 2021 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.

7
  • 11
    Thanks for your answer! I think this is actually the first answer that shows an objective way that for (;;) is better. Commented Sep 4, 2012 at 0:30
  • 13
    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. Commented Jul 24, 2014 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. Commented Jul 25, 2014 at 9: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. Commented Jul 25, 2014 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. Commented Jul 26, 2014 at 6:26
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
3
  • I doubt it's faster even in debug mode. Commented Apr 9, 2010 at 22:13
  • 115
    for_infinite is faster; 2 fewer characters to puts. Commented Apr 10, 2010 at 6: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. Commented Aug 31, 2022 at 16:27
21

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.

0
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 */
}
2
  • 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
    Commented Apr 9, 2010 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
    Commented Apr 9, 2010 at 23:35
16

What about (if your language supports it):

start:
/* BLAH */
goto start;
5
  • 1
    ...which should generate identical output in the hands of any reasonable compiler.
    – Ben Zotto
    Commented Apr 9, 2010 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
    Commented Apr 9, 2010 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
    Commented Oct 13, 2013 at 9:03
  • 1
    never ever ever use goto Commented Feb 2, 2014 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...)
    – user645280
    Commented Mar 31, 2014 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).

6
  • 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. Commented Apr 9, 2010 at 22:22
  • 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. Commented Apr 9, 2010 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. Commented Apr 9, 2010 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. Commented Apr 10, 2010 at 0: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. Commented Apr 10, 2010 at 9:11
12
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.

3
  • 9
    what version of visual studio are you using? With 2008 I don't get this warning, even at warning level 4. Commented Dec 4, 2010 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. learn.microsoft.com/en-us/cpp/error-messages/compiler-warnings/… Commented Mar 21, 2022 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 (<non-zero>) if the condition isn't clear to me yet. Commented Sep 1, 2023 at 6: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.

1
  • This is actually a very good point! Without optimization even modern compilers will differ by several instructions.
    – user645280
    Commented Mar 31, 2014 at 18:56
10

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

1
  • 3
    Yes, and I think some compilers warn on while (true) for the same reason they do on if (true). Commented Apr 9, 2010 at 22:12
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)

5
  • 3
    I believe the OP was referring to runtime speed, not typing speed.
    – Roger Pate
    Commented Apr 9, 2010 at 22:33
  • I know. Just had to cover that base, too. Commented Apr 9, 2010 at 22:49
  • 7
    s/personal preference/individual habit/
    – SamB
    Commented Apr 9, 2010 at 23:00
  • @SamB: Comment up-vote for s///. xD And 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. Commented Apr 10, 2010 at 0:20
  • Run time head -10 >/dev/null, type each 10 times, and measure the results. I bet you'll be faster at for(;;) unless you cheat. I was by about 14%. Commented Sep 25, 2015 at 23:26
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.

2
  • 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
    Commented Oct 15, 2014 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
    Commented Oct 16, 2014 at 20:02
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.

3
  • 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
    Commented Apr 9, 2010 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
    Commented Apr 9, 2010 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
    Commented Apr 10, 2010 at 15:37
4

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".

12
  • 3
    How frequently do you see people told to prefer ++i over i++? Commented Apr 10, 2010 at 6: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
    Commented Apr 10, 2010 at 9: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. Commented Apr 10, 2010 at 11:52
  • 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: stackoverflow.com/questions/926266/…. So I wonder about our priorities. Commented Apr 10, 2010 at 12: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. Commented Apr 10, 2010 at 15:10
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().

2
  • 4
    There is nothing clean about calling a function like sleep inside of a for loop like that
    – Greg
    Commented Oct 14, 2017 at 15:42
  • 1
    This is not equivalent. When there is a continue in the loop, the for loop sleeps but not the while loop. Commented Jan 5, 2021 at 20:07
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);
0
3

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

1
  • I care about speed. Especially if there is an optimization which will affect my code infinite times. Commented Mar 24, 2020 at 12:00
-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...

Not the answer you're looking for? Browse other questions tagged or ask your own question.