I see for(;;)
used much more frequently than while(1)
in the wild, and I am curious if there is any meaningful reason for this. Compiling using GCC with -O0 optimization, both statements yield a single jump instruction. Is it more than just a coding style? Are there any coding standards that state that for(;;)
is preferred over while(1)
? Is there some efficiency reason that I'm missing? I realize that the goal is usually to make code the most readable that it can be, but I don't see much of a difference between the two styles as far as readability to warrant such a stark difference in usage.

- 14,154
- 10
- 50
- 86

- 573
- 2
- 8
-
1maybe because while(1) involve a value (costant 1) whereas for(;;) Is pure statement – frhack Nov 23 '20 at 23:46
-
1Seems like some compilers generate different code https://godbolt.org/z/9Kqqex – Tony Tannous Nov 23 '20 at 23:49
2 Answers
while(1)
involves a constant which might result in an overhead when compiling without optimization such as pushing 1 and checking if the expression is z,n or positive.
MSVC demo with while(1)
https://godbolt.org/z/MMMT9n
$LN2@main:
mov eax, 1
test eax, eax
je SHORT $LN1@main
jmp SHORT $LN2@main
$LN1@main:
With for(;;)
$LN4@main:
jmp SHORT $LN4@main

- 14,154
- 10
- 50
- 86
-
1Very neat website. It seems that the switch from GCC to MSVC causes that extra inefficiency to show. – Kevin Montambault Nov 24 '20 at 00:04
-
3@KevinMontambault - is there any reason to talk about efficiency of not optimized code? With even default optimization, there will only be one `jmp`... – Vlad Feinstein Nov 24 '20 at 00:44
-
Who does actually care about the efficiency of the -O0 generated code? – 0___________ Nov 24 '20 at 02:09
-
@P__JsupportswomeninPoland no one should. But OP asked if there's any difference between them and I showed an example in which the generated code differs for `-O0` – Tony Tannous Nov 24 '20 at 10:24
With some older compilers, for example, Microsoft Visual Studio 2015 before update 3, the while(1)
construct will trigger a warning about conditional expression being constant, see Remarks section for warning C4127.
A related question was asked on Stack Overflow over ten years ago about this, see Why MSVC generates warning C4127 when constant is used in “while”.
I remember stumbling upon this, back in the days when we were using Visual Studio 2012. Nowadays, this seems to be sorted out, but still, the for(;;)
form seems more idiomatic to me.

- 1,846
- 1
- 18
- 22