1

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.

Tony Tannous
  • 14,154
  • 10
  • 50
  • 86

2 Answers2

2

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
Tony Tannous
  • 14,154
  • 10
  • 50
  • 86
2

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.

heap underrun
  • 1,846
  • 1
  • 18
  • 22