您现在的位置是:亿华云 > 人工智能
你会用while(1)还是for(;;)写循环代码?
亿华云2025-10-02 18:49:17【人工智能】1人已围观
简介看代码看到for(;;),然后觉得为什么不写成while(1)呢,所以就做了下面的测试。网上有解释,因为while需要做一次判断,理论上执行会花费的时间更久,for(;;)只是执行了两次空语句,执行会
看代码看到for(;;),用e还然后觉得为什么不写成while(1)呢,写循环所以就做了下面的代码测试。
网上有解释,用e还因为while需要做一次判断,写循环理论上执行会花费的代码时间更久,for(;;)只是用e还执行了两次空语句,执行会更快
for.c
#include <stdio.h> int main(){ for(;;) printf("This is a loop\n"); return 0; }while.c
#include <stdio.h> int main(){ while(1) printf("This is a loop\n"); return 0; }goto.c
#include <stdio.h> int main(){ start: printf("This is a loop\n"); goto start; return 0; }用gcc -S xxx.c 执行后得到三个文件
for.s
.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,"",@progbitswhile.s
.file "while.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,"",@progbitsgoto.s
.file "goto.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,"",@progbitsgcc 版本
gcc (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0 Copyright (C) 2017 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.在上面测试结束后,我还特意打开了我的代码keil软件,服务器租用结果发现两个生成的用e还机器码都是一样的。
所以说,写循环如果在项目中遇到这样的代码写法,就不要再感觉奇怪了,用e还他们都是写循环没啥问题的。
只不过for(;;)看起来更优雅一些。网站模板代码
还有一种情况while(1)里面的1是一个常量,在一些编译器中,设置的检查规则比较高的话,会提示一个警告,for(;;)就不会存在这种问题,因为里面就没有变量,也没有常量。
亿华云计算很赞哦!(594)
上一篇: 数据中心是干什么的?
下一篇: 智能PDU的主要有哪些实用功能?