看代码看到for(;;),然后觉得为什么不写成while(1)呢,所以就做了下面的测试。

网上有解释,因为while需要做一次判断,理论上执行会花费的时间更久,for(;;)只是执行了两次空语句,执行会更快
for.c
- #include
 - int main(){
 - for(;;)
 - printf("This is a loop\n");
 - return 0;
 - }
 
while.c
- #include
 - int main(){
 - while(1)
 - printf("This is a loop\n");
 - return 0;
 - }
 
goto.c
- #include
 - 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,"",@progbits
 
while.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,"",@progbits
 
goto.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,"",@progbits
 
gcc 版本
- 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软件,结果发现两个生成的机器码都是一样的。
所以说,如果在项目中遇到这样的写法,就不要再感觉奇怪了,他们都是没啥问题的。
只不过for(;;)看起来更优雅一些。
还有一种情况while(1)里面的1是一个常量,在一些编译器中,设置的检查规则比较高的话,会提示一个警告,for(;;)就不会存在这种问题,因为里面就没有变量,也没有常量。
                当前题目:你会用while(1)还是for(;;)写循环代码?
                
                文章网址:http://www.csdahua.cn/qtweb/news29/432079.html
            
网站建设、网络推广公司-快上网,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 快上网