Is for(;;) Faster Than while(1) in C? A Practical Comparison
The article compares the infinite loop constructs for(;;) and while(1) in C by compiling simple programs, examining the generated assembly with gcc, and shows that both produce identical machine code, while also noting compiler warnings and style preferences.
Test programs
Three minimal C programs that print an infinite‑loop message using different constructs.
#include <stdio.h>
int main() {
for(;;)
printf("This is a loop
");
return 0;
} #include <stdio.h>
int main() {
while(1)
printf("This is a loop
");
return 0;
} #include <stdio.h>
int main() {
start:
printf("This is a loop
");
goto start;
return 0;
}Generated assembly
Each source file was compiled with gcc -S file.c using GCC 7.5.0 on Ubuntu 18.04. The produced assembly for all three programs is identical, illustrating that the three loop forms generate the same low‑level code.
.file "for.c"
.text
.section .rodata
.LC0:
.string "This is a loop"
.text
.globl main
.type main, @function
main:
.LFB0:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
.L2:
leaq .LC0(%rip), %rdi
call puts@PLT
jmp .L2
.cfi_endproc
.LFE0:
.size main, .-main
.ident "GCC: (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0"
.section .note.GNU-stack,"",@progbitsCompiler version
gcc (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0Additional observations
The same assembly is produced by the Keil IDE, confirming that the loop forms are equivalent across toolchains.
Some compilers issue a warning for while(1) because the constant 1 may be flagged by strict warning settings; for(;;) contains no explicit condition and therefore avoids that warning.
Conclusion
Both for(;;) and while(1) implement an infinite loop with no measurable performance difference; the generated assembly is identical. The choice can be based on readability or compiler‑warning preferences, with for(;;) often considered slightly more elegant.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
